C # how to update a file (keep old data)

Now I write to a file:

TextWriter tw = new StreamWriter(@"D:/duom.txt");
tw.WriteLine("Text1");

      

When I write a second time, all data is deleted and new is written.

How do I update my data? Leave the old data and add new ones

+2


a source to share


6 answers


One way is to specify true

for a flag Append

(in one of the constructor overloads StreamWriter

):

TextWriter tw = new StreamWriter(@"D:/duom.txt", true);

      



Note. Don't forget to wrap the operator using

.

+3


a source


Use FileMode.Append



using (FileStream fs = new FileStream(fullUrl, FileMode.Append, FileAccess.Write))
{
  using (StreamWriter sw = new StreamWriter(fs))
  {

  }
}

      

+1


a source


You need to use an overload constructor with an add flag, and don't forget to make sure your stream is closed, complete:

using (TextWriter tw = new StreamWriter(@"D:\duom.txt", true))
{
    tw.WriteLine("Text1");
}

      

+1


a source


You must specify the FileMode . You can use:

var tw = File.Open(@"D:\duom.txt", FileMode.Append);
tw.WriteLine("Text1");

      

0


a source


TextWriter tw = new StreamWriter(@"D:/duom.txt", true);

      

Will be added to the file instead of writing it

0


a source


You can use File.AppendText like this:

TextWriter tw = File.AppendText(@"D:/duom.txt");
tw.WriteLine("Text1");
tw.Close();

      

0


a source







All Articles