c# 基础任务1

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() + "\r\n";             Exception error = e.Exception as Exception;             if (error != null)             {                 str = string.Format(strDateInfo + "异常类型:{0}\r\n异常消息:{1}\r\n异常信息:{2}\r\n",                      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() + "\r\n";             if (error != null)             {                 str = string.Format(strDateInfo + "异常信息:{0};\n\r堆栈信息:{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) + "\\";
        }

 

posted @ 2017-12-12 09:43  laolv  阅读(260)  评论(0编辑  收藏  举报