2

Now I'm writing to a file:

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

When i writen second time all data delete and write new.

How update data? Leave old data and add new

Joel Coehoorn
  • 380,066
  • 110
  • 546
  • 781
lolalola
  • 3,689
  • 19
  • 57
  • 92

6 Answers6

3

One way is to specify true for the Append flag (in one of the StreamWriter constructor overloads):

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

NB: Don't forget to wrap in a using statement.

Mitch Wheat
  • 288,400
  • 42
  • 452
  • 532
1

Use FileMode.Append

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

  }
}
CRice
  • 11,823
  • 7
  • 55
  • 81
1

You need to use the constructor overload with the append flag, and don't forget to make sure your stream is closed when you're finished:

using (TextWriter tw = new StreamWriter(@"D:\duom.txt", true))
{
    tw.WriteLine("Text1");
}
Joel Coehoorn
  • 380,066
  • 110
  • 546
  • 781
0

You must specify the FileMode. You can use:

var tw = File.Open(@"D:\duom.txt", FileMode.Append);
tw.WriteLine("Text1");
Reed Copsey
  • 539,124
  • 75
  • 1,126
  • 1,354
0
TextWriter tw = new StreamWriter(@"D:/duom.txt", true);

Will append to the file instead of overwriting it

JHurrah
  • 1,978
  • 16
  • 12
0

You could use File.AppendText like this:

TextWriter tw = File.AppendText(@"D:/duom.txt");
tw.WriteLine("Text1");
tw.Close();
Joe Axon
  • 146
  • 7