开发者

C# how to update file(leave old data)

开发者 https://www.devze.com 2022-12-30 14:20 出处:网络
Now I\'m writing to a file: TextWriter tw = new StreamWriter(@\"D:/duom.txt\"); tw.WriteLine(\"Text1\");

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

精彩评论

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

关注公众号