using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.IO; namespace HotelPms.Share.Windows.Util { public class UnhandledExceptionListener { public static void Execute() { Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); if (Application.StartupPath.CompareTo(Environment.CurrentDirectory) != 0) { Environment.CurrentDirectory = Application.StartupPath; } } private static void WriteUnhandledExceptionLog(object data, string title) { try { string file = Application.StartupPath + @"\UnhandledException.log"; if (File.Exists(file)) { FileInfo fileInfo = new FileInfo(file); if (fileInfo.Length > 1024 * 1024) { string bkfile = string.Format(@"\UnhandledException{0}.log", DateTime.Now.ToString("yyyyMMddHHmmss")); File.Copy(file, bkfile, true); File.Delete(file); } } using (System.IO.FileStream fs = new System.IO.FileStream(file, System.IO.FileMode.Append, System.IO.FileAccess.Write)) { using (System.IO.StreamWriter w = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8)) { w.WriteLine(string.Format("y{0}z{2}F{1}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss fff"), data, title)); } } } catch { } } private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { WriteUnhandledExceptionLog(e.Exception, "Application_ThreadException"); } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { WriteUnhandledExceptionLog(e.ExceptionObject, "CurrentDomain_UnhandledException" + "F" + e.IsTerminating.ToString()); } } }