Moccassin
Moccassin

Reputation: 169

Cannot access the file ASP.NET and c#

I need some help. I'm trying to write/create a log file for error logging of our asp.net web app. Previously my code is working without issue, but now I encountered an error "The process cannot access the file because it is being used by another process" even though I did not change anything in my code. But in any case I need to resolve this issue. Please help. What's wrong in my code? Thanks.

        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();

Upvotes: 1

Views: 310

Answers (1)

Damith
Damith

Reputation: 63065

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());
}

Upvotes: 2

Related Questions