0

当应用程序出现错误时,我正在尝试将一些信息写入文本文件。我将此代码添加到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,问题就解决了

4

3 回答 3

1

您的代码的一个问题是您的通话没有using阻塞。File.Create问题是这个方法创建一个文件并返回一个流。当您尝试写入文件时,该流很可能仍会锁定该文件。

要解决此问题,您可以使用一个空using块来关闭并处理流,如下所示:

if (!File.Exists(path))
{
    using (File.Create(path)) { }
}

一个可能并不总是引起人们注意的相关问题是您没有处理您的TextWriter. 您还应该将使用它的代码包装在一个using块中,以确保它得到处理(并且您可以删除对的调用,.Close因为这会自动发生):

using (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(@"}");
}
于 2015-05-06T19:42:52.047 回答
0

您的问题可能是由于使用Server.MapPath.

尝试改变:

string path = Server.MapPath("Error.txt");

类似于:

string path = String.Format("{0}\\{1}", HttpRuntime.AppDomainAppPath, "Error.txt");
于 2015-05-06T19:38:36.770 回答
-2

我只需要以管理员身份运行visual studio,不要浪费时间尝试添加更多答案\评论,这个问题就解决了

于 2015-05-06T19:53:09.023 回答