Write to text file in C# using TextWriter

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: