Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

c# - Append lines to a file using a StreamWriter

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...