开发者

C# how to update file(leave old data)

Now I'm writing to a file:

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

When i writen second time all data de开发者_高级运维lete and write new.

How update data? Leave old data and add new


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.


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");
}


Use FileMode.Append

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

  }
}


You must specify the FileMode. You can use:

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


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

Will append to the file instead of overwriting it


You could use File.AppendText like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜