Append text using StreamWriter

keynesiancross picture keynesiancross · Jan 13, 2012 · Viewed 100k times · Source

This is probably a pretty simple question. In C# I'm trying to write a simple method, called my "DebugWrite" method, to write out any exceptions caught within my program to a text file stored locally. My current code only writes a new file every time, using StreamWriter

How do you program it to check if the file already exists, and if so to append to the current text?. IE:

If(~Exist(debug.txt)
{
  Write new debug.txt.
}
else if(exist(debug.txt))
{
  Append new text.
}

Answer

Mike Mooney picture Mike Mooney · Jan 13, 2012
using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
  writer.WriteLine("whatever you text is");
}

The second "true" parameter tells it to append.

http://msdn.microsoft.com/en-us/library/36b035cb.aspx