user1659510
user1659510

Reputation: 283

Error occured While writing to the file

I am creating the File. At first time after creating the file, I'm immediately going to open a file but it shows error:

"The process cannot access the file 'C:\ProjectWork\Websites3\LogsArpita\ErrorLogs\Error_Log_24_4_2014.txt' because it is being used by another process."

What does it means? How can I open a file immediately for further write operation. I have tried with following code.

FileName = String.Concat("Error_Log_", DateTimeStamp + ext);

if (!File.Exists(Server.MapPath("~/LogsArpita/ErrorLogs/" + FileName)))
{
    File.Create(Server.MapPath("~/LogsArpita/ErrorLogs/" + FileName));
}

//Error occured here, below line
StreamWriter tw = new StreamWriter(Server.MapPath("~/LogsArpita/ErrorLogs/" +    FileName), true);

tw.WriteLine("");
tw.Write("\"" + DateTimeStampLog + "\",");
tw.Write("\"Assignments.aspx\",");
tw.Write("\"" + ErrorMessage + "\",");
tw.Write("\"" + TransactVariable + "\"");
tw.Close();

Upvotes: 0

Views: 128

Answers (1)

Mike Norgate
Mike Norgate

Reputation: 2431

You do not need the File.Create because the StreamWriter constructor will create the file if it does not exist

This is what the msdn documentation says:

Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.

Upvotes: 2

Related Questions