title: StreamWriter file in use by another process - Writing to fast too frequently?
body: <p>I'm getting an error with StreamWriter that the file is in use by another process, but I believe it may be down to the speed at which I'm writing the file or more specifically the speed of it being opened/closed.</p>
  
  <p>The code is as follows:</p>
  
  <pre><code>    public static void writeLog(string msg)
      {
          StreamWriter log;
          string currentMonth = DateTime.Now.ToString("MMM");
          string currentYear = DateTime.Now.ToString("yyyy");
          string directoryName = currentMonth + "-" + currentYear;
  
          if (!Directory.Exists(@"C:\AutoSkill\LogFiles\" + directoryName + @"\"))
          {
              Directory.CreateDirectory(@"C:\AutoSkill\LogFiles\" + directoryName + @"\");
          }
  
          DateTime dt = DateTime.Now;
          string date = dt.ToString("dd-MM-yy");
  
          if (!File.Exists(@"C:\AutoSkill\LogFiles\" + directoryName + @"\" + date + ".txt"))
          {
              log = new StreamWriter(@"C:\AutoSkill\LogFiles\" + directoryName + @"\" + date + ".txt");
          }
          else
          {
              log = File.AppendText(@"C:\AutoSkill\LogFiles\" + directoryName + @"\" + date + ".txt");
          }
  
          try
          {
              log.WriteLine(msg);
          }
          catch (Exception err)
          {
              Console.WriteLine("There was an error writing to the log file.");
              Console.WriteLine(err.Message);
          }
          log.Close();
      }
  </code></pre>
  
  <p>So I'm closing the log each time I'm done writing to it, but I'm writing all out my output from the console screen to the file to keep track of what actually happened; sometimes the lines are only a few milliseconds apart if the action that was taken was quick or just returned null.</p>
  
  <p>Am i getting this error due to speed of writing to the file? Is there a better way to handle writing a log file?</p>