Wednesday, April 4, 2007

Log file lock problem

If you need your own logging class that will log messages to a file, then this is not a hard task. But when you need to write to log file frequently, then can comes problem of locked file, because previous operation of writing to file didn't finished yet and file is still locked. Here is a class that i wrote that helps me to override this problem:

public class MyLogger
{
   private String _LogFilePath;
   private String _Name;
   private List<String> _Waiting = new List<String>();
   public MyLogger(String name)
   {
      _LogFilePath = Path.GetDirectoryName(
         GetType().Assembly.Location) + @"\Log\";
      _Name = name;
      if (!Directory.Exists(LogFilePath))
         Directory.CreateDirectory(LogFilePath);
   }

   public void WriteToLogFile(String message)
   {
      _Waiting.Add(DateTime.Now.ToString("HH:mm:ss.fffff ") + message);
      String filePath = String.Format("{0}{1}_{2}.log",
         LogFilePath,
         DateTime.Now.ToString("yyyyMMdd"),
         Name);
      try
      {
         if (!File.Exists(filePath))
         {
            using (StreamWriter sw = File.CreateText(filePath))
            {
               foreach (String s in _Waiting)
               {
                  sw.WriteLine(s);
               }
               _Waiting.Clear();
            }
         }
         else
         {
            using (StreamWriter sw = File.AppendText(filePath))
            {
               foreach (String s in _Waiting)
               {
                  sw.WriteLine(s);
               }
               _Waiting.Clear();
            }
         }
      }
      catch(Exception ex)
      {
         Debug.WriteLine(String.Format("Unable to add log in {0} {1}", Name, ex.Message));
      }
   }
}

Monday, April 2, 2007

ParseExact

When converting string to DateTime then you should never use Parse method. Instead you should always use ParseExact, and from .NET 2.0 you can use also TryParseExact.