title: How to log exception to file
body: <p>I have been trying to log exceptions to a file. I can get the exception with all its details and when I step through the class the <code>StreamWriter logWriter</code> doesn't seem to do what I thought it would do.</p>
  
  <pre><code> public static void Write(Exception exception)
  {
      string logfile = String.Empty;
      try
      {
          logfile = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ErrorLog"]).ToString();
          StreamWriter logWriter;
          if (File.Exists(logfile))
          {
              logWriter = File.AppendText(logfile);
          }
          else
          {
              logWriter = File.CreateText(logfile);
              logWriter.WriteLine("=&gt;" + DateTime.Now + " " + " An Error occurred: " + exception.StackTrace +
                                  " Message: " + exception.Message + "\n\n");
              logWriter.Close();
              throw exception;
          }
      }
      catch (Exception e)
      {
          throw;
      }
  
  }
  </code></pre>
  
  <p>I would of thought the logWriter would of written the exception details to the File.AppendText(logfile)<code>but it doesn't and just jumps straight out the if statement. All the details of the exception are in the else statement, I have tried to put this in the</code>if` condition but throws an exception! </p>
  
  <p>How can I write the exception to the file. I got the code from <a href="http://www.codeproject.com/Articles/550510/Exception-Handling-and-NET" rel="nofollow">CodeProject</a>. Everything thing works fine except writing the exception to the file.</p>