Wednesday, May 08, 2013

Logging Exception to a text file when catch(Exception e)


catch (Exception e)
            {
                StringBuilder sb2 = new StringBuilder();
                sb2.Append("Exception Date/Time: " + DateTime.Now);
                sb2.Append(System.Environment.NewLine);
                sb2.Append(System.Environment.NewLine);
                sb2.Append("Exception Message: " + e.Message);
                sb2.Append(System.Environment.NewLine);
                sb2.Append(System.Environment.NewLine);
                sb2.Append("Stack Trace:" + e.StackTrace);
                sb2.Append(System.Environment.NewLine);
                sb2.Append(System.Environment.NewLine);
                sb2.Append("Inner Exception:" + e.InnerException);
                sb2.Append(System.Environment.NewLine);
                sb2.Append(System.Environment.NewLine);
                sb2.Append("Data:" + e.Data);
 
                using (StreamWriter sw = File.AppendText("ErrorLog.txt"))
                {
                    sw.Write(sb2.ToString());
                    sw.Close();
                }


Of course you can expand this to catch different exceptions.


You could also write to the Event Log, but unless you area  system admin or have access to event logs you are SOL..

http://support.microsoft.com/kb/307024

No comments:

How to Secure Your Personal Devices

Understanding the Importance of Device Security Risks Associated with Unsecured Devices Personal devices such as smartphones, laptops, t...