c# - How to create a file if it doesn't exist yet and add new text? -


my code works fine creating file if doesn't exist , inserting new text, or if file exists, rewrites current contents.

path = @"c:\my folder\data.txt";  filestream files = null;  bool done = false;  while (!done) {     done = true;      try     {         filestream filestream = file.open(path, filemode.openorcreate);         filestream.setlength(0);         filestream.close();         files = file.openwrite(path);     }     catch (ioexception ex)     {         done = false;         // thread.sleep(3);     } }      using (streamwriter fs = new streamwriter(files)) {     fs.write(texta);     fs.close(); };  files.dispose(); 

now need change doesn't rewrites contents anymore instead add new text previous contents. second, need know if file empty , in case insert texta or if there contents , in case add textb.

try this

        string path = @"your file path";          bool done = false;          while (!done)         {             done = true;              try             {                 filestream filestream = null;                 filestream = file.open(path, file.exists(path) ? filemode.append : filemode.openorcreate);                  using (streamwriter fs = new streamwriter(filestream))                 {                     fs.writeline(filestream.length == 0 ? "text a" : "text b");                 };                 filestream.close();             }             catch (ioexception)             {                 done = false;              }          } 

Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - IE9 error '$'is not defined -