31

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.
}
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
keynesiancross
  • 3,441
  • 15
  • 47
  • 87
  • 2
    You're already using `StreamWriter` but haven't figured that it accepts a second parameter [append](http://msdn.microsoft.com/en-us/library/36b035cb(v=VS.80).aspx) which does what you want ? – Christian.K Jan 13 '12 at 17:56
  • There is one more alternate approach to use **File.AppendText** https://stackoverflow.com/a/41396275/3057246 – Vinod Srivastav Jun 12 '17 at 03:01

2 Answers2

89
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

Mike Mooney
  • 11,729
  • 3
  • 36
  • 42
2

Also look at log4net, which makes logging to 1 or more event stores — whether it's the console, the Windows event log, a text file, a network pipe, a SQL database, etc. — pretty trivial. You can even filter stuff in its configuration, for instance, so that only log records of a particular severity (say ERROR or FATAL) from a single component or assembly are directed to a particular event store.

http://logging.apache.org/log4net/

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135