Append lines to a file using a StreamWriter

2018-12-31 20:33发布

I want to append lines to my file. I am using a StreamWriter:

StreamWriter file2 = new StreamWriter(@"c:\file.txt");
file2.WriteLine(someString);
file2.Close();

The output of my file should be several strings below each other, but I have only one row, which is overwritten every time I run this code.

Is there some way to let the StreamWriter append to an existing file?

10条回答
高级女魔头
2楼-- · 2018-12-31 21:10

One more simple way is using the File.AppendText it appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist and returns a System.IO.StreamWriter

using (System.IO.StreamWriter sw = System.IO.File.AppendText(logFilePath + "log.txt"))
{                                                
    sw.WriteLine("this is a log");
}
查看更多
人气声优
3楼-- · 2018-12-31 21:12

Use this instead:

new StreamWriter("c:\\file.txt", true);

With this overload of the StreamWriter constructor you choose if you append the file, or overwrite it.

C# 4 and above offers the following syntax, which some find more readable:

new StreamWriter("c:\\file.txt", append: true);
查看更多
谁念西风独自凉
4楼-- · 2018-12-31 21:13

Use this StreamWriter constructor with 2nd parameter - true.

查看更多
初与友歌
5楼-- · 2018-12-31 21:14

Try this:

StreamWriter file2 = new StreamWriter(@"c:\file.txt", true);
file2.WriteLine(someString);
file2.Close();
查看更多
登录 后发表回答