Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# add text to text file without rewriting it?

Let's say I have the following code:

StreamWriter sw = new StreamWriter(File.OpenWrite(Path));
sw.Write("Some stuff here");
sw.Dispose();

This code replaces the contents of the file with "Some stuff here," however I would like to add text to the file rather than replacing the text. How would I do this?

like image 554
Oztaco Avatar asked Dec 04 '22 04:12

Oztaco


2 Answers

You could use the File.AppendAllText method and replace the 3 lines of code you have with:

File.AppendAllText(Path, "blah");

This way you don't have to worry about streams and disposing them (even in the event of an exception which by the way you are not doing properly) and the code is pretty simple and straightforward to the point.

like image 120
Darin Dimitrov Avatar answered Dec 21 '22 15:12

Darin Dimitrov


You need to tell the StreamWriter you want to append:

var sw = new StreamWriter(path, true);

File.OpenWrite doesn't support appending.

like image 23
zmbq Avatar answered Dec 21 '22 15:12

zmbq