2014-04-24 123 views
0

我正在創建文件。創建文件後第一次,我立即打開一個文件,但它顯示錯誤:寫入文件時發生錯誤

"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."

這是什麼意思?如何立即打開文件以進一步寫入操作。我嘗試了以下代碼。

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

回答

2

你不需要File.Create因爲StreamWriter構造函數將創建該文件,如果不存在

它這是在MSDN文檔說:

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.

+1

而且'File.Create'方法創建並打開文件流並返回打開的流。所以當你使用'File.Create'時,你應該處理返回的流,否則你每次嘗試打開該文件都會失敗。但是,您可以使用'StreamWriter'構造函數並讓它工作。 –