在Program.cs中的Main方法中加入以下代码
1
2
3
4
5
6
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += Application_ThreadException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
在Program.cs中实现这个两个异常捕获方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
using (FileStream efs = new FileStream("./error.txt", FileMode.Append))
{
byte[] data = System.Text.Encoding.Default.GetBytes("CurrentDomain_UnhandledException::" + e.ToString() + ",object:" + e.ExceptionObject.ToString());
efs.Write(data, 0, data.Length);
}
}
private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
using (FileStream efs = new FileStream("./error.txt", FileMode.Append))
{
byte[] data = System.Text.Encoding.Default.GetBytes("Application_ThreadException:" + e.ToString());
efs.Write(data, 0, data.Length);
}
}