As the title said, here how you can create useful log files for your applications. This code creates the folder where you want to create the files (if the folder doesn’t exist) and creates one file per day.

public static void VerifyDir(string path)
{
    try
    {
        DirectoryInfo dir = new DirectoryInfo(path);
        if (!dir.Exists)
        {
            dir.Create();
        }
        }
    catch{}
}

public static void Logger(string lines)
{
    string path = "C:/Log/";
    VerifyDir(path);
    string fileName = DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() +         DateTime.Now.Year.ToString() + "_Logs.txt";
    try
    {
        System.IO.StreamWriter file = new System.IO.StreamWriter(path + fileName,         true);
        file.WriteLine(DateTime.Now.ToString() + ": " + lines);
        file.Close();
    }
    catch (Exception) { }
}

VerifyDir checks if a folder exists and, if not, creates it.

Logger write what you need in the file, with a datetime info at the beginning of the row.

Here a little sample of a call:


Utility.Logger("My log string");

Advertisements