How to: Open and Append to a Log File
StreamWriter and StreamReader write characters to and read characters from streams. The following code example opens the log.txt file for input, or creates the file if it does not already exist, and appends information to the end of the file. The contents of the file are then written to standard output for display. As an alternative to this example, the information could be stored as a single string or string array, and the WriteAllText or WriteAllLines method could be used to achieve the same functionality.
Note |
|---|
Visual Basic users may choose to use the methods and properties provided by the Log class or FileSystem class for creating or writing to log files. |
using System; using System.IO; class DirAppend { public static void Main() { using (StreamWriter w = File.AppendText("log.txt")) { Log("Test1", w); Log("Test2", w); // Close the writer and underlying file. w.Close(); } // Open and read the file. using (StreamReader r = File.OpenText("log.txt")) { DumpLog(r); } } public static void Log(string logMessage, TextWriter w) { w.Write("\r\nLog Entry : "); w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString()); w.WriteLine(" :"); w.WriteLine(" :{0}", logMessage); w.WriteLine ("-------------------------------"); // Update the underlying file. w.Flush(); } public static void DumpLog(StreamReader r) { // While not at the end of the file, read and write lines. string line; while ((line = r.ReadLine()) != null) { Console.WriteLine(line); } r.Close(); } }
The example is quite nice but I just want to mention that the
w.Close()
call is not required and simply has the consequence, that w is disposed twice! Code Analysis (Visual Stuop 2010 Premium and above) also shows a warming:
CA2202 : Microsoft Usage : Object 'w' can be disposed more than once in method 'Main()'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.
A little deeper description of the core:
using statement will make sure, that Dispose() is called at the end.
Dispose() is calling Close()
Close() is calling Dispose(true) and GC.SupressFinalize(this);
So the Dispose(true) is done twice in the given example.
(Close() and Dispose is implemented inside Stream. The implementation could be checked with a tool like dotPeek provided by JetBrains )
I hope this addition is helpfull for others.
With kind regards,
Konrad
- 4/10/2012
- Konrad Neitzel
- 12/16/2011
- JayCalifornia
Note