1

我需要一些帮助。我正在尝试为我们的 asp.net Web 应用程序的错误记录编写/创建一个日志文件。以前我的代码可以正常工作,但现在我遇到了一个错误“该进程无法访问该文件,因为它正在被另一个进程使用”,即使我没有更改我的代码中的任何内容。但无论如何我需要解决这个问题。请帮忙。我的代码有什么问题?谢谢。

        StreamWriter file;
        if (logDetails.User.Length == 0)
        {
            logDetails.User = "Administrator";
        }

        string fileName = Path.Combine(filePath, appFile) + "_" + logDetails.User + "_" + DateTime.Now.ToString("yyyyMMdd") + ".txt";

        StringBuilder builder = new StringBuilder();
        builder = new StringBuilder();

        if (!File.Exists(fileName))
        {
            file = new StreamWriter(fileName);
            builder.AppendFormat("{0}\t\t\t{1}\t{2}\t{3}\t\t\t\t\t\t{4}\t\t\t\t{5}", "DATE", "PRIORITY", "SEVERITY", "MESSAGE", "EXCEPTION TYPE");
            builder.Append(Environment.NewLine);
        }
        else
        {
            file = File.AppendText(fileName);  //**exception thrown here**
        }

        builder.Append(String.Format("{0}\t{1}\t\t{2}\t{3}\t{4}\t\t{5}", DateTime.Now.ToString(), logDetails.detail1, logDetails.detail2, logDetails.detail3+ logDetails.detail4, logDetails.detail5));

        builder.AppendLine();
        builder.Append(String.Format("STACKTRACE"));
        builder.AppendLine(logDetails.StackTrace);
        file.WriteLine(Convert.ToString(builder));
        file.Close();
4

1 回答 1

2
StringBuilder builder = new StringBuilder();
if (!File.Exists(fileName))
{
    builder.AppendFormat("{0}\t\t\t{1}\t{2}\t{3}\t\t\t\t\t\t{4}\t\t\t\t{5}", "DATE", "PRIORITY", "SEVERITY", "MESSAGE", "EXCEPTION TYPE");
    builder.Append(Environment.NewLine);
}
builder.Append(String.Format("{0}\t{1}\t\t{2}\t{3}\t{4}\t\t{5}", DateTime.Now.ToString(), logDetails.detail1, logDetails.detail2, logDetails.detail3+ logDetails.detail4, logDetails.detail5));

builder.AppendLine();
builder.Append(String.Format("STACKTRACE"));
builder.AppendLine(logDetails.StackTrace);

using (StreamWriter sw = File.AppendText(path)) 
{
    sw.WriteLine(builder.ToString());
}
于 2013-10-24T04:32:03.933 回答