当应用程序出现错误时,我正在尝试将一些信息写入文本文件。我将此代码添加到Application_Error
方法中,global.asax
但它仍然不起作用:
void Application_Error(object sender, EventArgs e)
{
string path = Server.MapPath("Error.txt");
Exception ex = Server.GetLastError();
if (!File.Exists(path))
{
File.Create(path);
}
if (File.Exists(path))
{
TextWriter tw = new StreamWriter(path, true);
tw.WriteLine("{0} : An Error Has Occurred, Error Description",DateTime.Now.ToString());
tw.WriteLine(@"{");
tw.WriteLine("Error Message: {0}", ex.Message);
tw.WriteLine("Source: {0}", ex.Source);
if (ex.StackTrace != null) tw.WriteLine("StackTrace: {0}", ex.StackTrace);
tw.WriteLine(@"}");
tw.Close();
}
}
如果这很重要,我还会在出现错误时重定向到错误页面,这是 web.config 文件:
<customErrors mode="On" defaultRedirect="ASPX/Error.aspx" redirectMode="ResponseRedirect">
<error statusCode="404" redirect="ASPX/Error404.aspx"/>
</customErrors>
那么你知道我的代码有什么问题吗?如何让它将文本写入文件?
编辑: 我只需要以管理员身份运行vs,问题就解决了