How can I easily log a message to a file for debugging purposes?

Often, you need a way to monitor your applications once they are running on the server or even at the customer site — away from your Visual Studio debugger. In those situations, it is often helpful to have a simple routine that you can use to log messages to a text file for later analysis.

Here’s a simple routine that has helped me a lot for example when writing server applications without an user interface:

using System.IO;
public string GetTempPath()
    string path = System.Environment.GetEnvironmentVariable("TEMP");
    if (!path.EndsWith("\\")) path += "\\";
    return path;

public void LogMessageToFile(string msg)
    System.IO.StreamWriter sw = System.IO.File.AppendText(
        GetTempPath() + "My Log File.txt");
        string logLine = System.String.Format(
            "{0:G}: {1}.", System.DateTime.Now, msg);

With this simple method, all you need to do is to pass in a string like this:

LogMessageToFile("Hello, World");

The current date and time are automatically inserted to the log file along with your message.

[author: Jani Järvinen, C# MVP]