C# add text to text file without rewriting it?

Oztaco - Reinstate Monica C. picture Oztaco - Reinstate Monica C. · Mar 4, 2012 · Viewed 12.1k times · Source

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?

Answer

Darin Dimitrov picture Darin Dimitrov · Mar 4, 2012

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.