Write to text file in C# using TextWriter

2009/10/07

Very simple:

    public static void WriteLog(String logFileName, String msg)
    {
        try
        {
            TextWriter writer = new StreamWriter(logFileName, true);
            writer.WriteLine(DateTime.Now.ToString("mm:ss") + " " + msg);
            writer.Flush();
            writer.Close();
            writer = null;
        }
        catch
        {
        }
    }

The second parameter of the StreamWriter constructor specifies if the text will be appended to the file; if set to false, the file will be overwritten.


%d bloggers like this: