1.winform系统全局异常布局处理。
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
//处理UI线程异常
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
//处理非UI线程异常
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
1. static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) {
string str = ""; string strDateInfo = "出现应用程序未处理的异常:" + DateTime.Now.ToString() + " "; Exception error = e.Exception as Exception; if (error != null) { str = string.Format(strDateInfo + "异常类型:{0} 异常消息:{1} 异常信息:{2} ", error.GetType().Name, error.Message, error.StackTrace); } else { str = string.Format("应用程序线程错误:{0}", e); }
writeLog(str); // MessageBox.Show("发生致命错误,请及时联系作者!", "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error); }
2. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { string str = ""; Exception error = e.ExceptionObject as Exception; string strDateInfo = "出现应用程序未处理的异常:" + DateTime.Now.ToString() + " "; if (error != null) { str = string.Format(strDateInfo + "异常信息:{0}; 堆栈信息:{1}", error.Message, error.StackTrace); } else { str = string.Format("Application UnhandledError:{0}", e); }
writeLog(str); // MessageBox.Show("发生致命错误,请停止当前操作并及时联系作者!", "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error); }
2.存储异常信息
private static object obj = new object();
static void writeLog(string str) { lock (obj) { if (!Directory.Exists(getPathStr()+"ErrLog")) { Directory.CreateDirectory(getPathStr() + "ErrLog"); }
using (StreamWriter sw = new StreamWriter(getPathStr() + "ErrLog\" + DateTime.Now.ToLongDateString().ToString() + ".txt", true)) { sw.WriteLine(str); sw.WriteLine("---------------------------------------------------------"); sw.Close(); } } }
3. 获取系统运行路径
static string getPathStr()
{
return Application.ExecutablePath.Substring(0, Application.ExecutablePath.Length - 4) + "\";
}