簡體   English   中英

該進程無法訪問文件'directory \\ file',因為它正被C#File Writer中的另一個進程使用

[英]The process can not access the file 'directory\file' because it is being used by another process in C# File Writer

每當我嘗試保存在現有文件上時,都會收到此錯誤:

該進程無法訪問該文件,因為該文件正在被另一個進程使用

當文件不存在時,它可以工作,但是當我嘗試再次寫入文件時,將顯示錯誤。 那時我沒有訪問或使用文件。

這是代碼:

string directory = filepath + "Updates\\" + dir;
if(!Directory.Exists(directory))
{
    Directory.CreateDirectory(directory);
}
remarks = remarks.Trim();
remarks = remarks.Replace("\r\n","<br>");
remarks = remarks.Replace(",","|");
string file = directory + "\\" +  getIndex(barcode) + ".asdt";
StreamWriter writer = new StreamWriter(file,true);
writer.WriteLine(username + "," + barcode + "," + DateTime.Now.ToString("yyyy-MM-dd HH.mm")+ "," + remarks);
writer.Close();

當我檢查它時,該錯誤發生在行上:

StreamWriter writer = new StreamWriter(file,true);

這可能是什么原因?

您的程序可能無法正確處理文件流,從而使文件保持打開狀態。

使用using語句確保正確處置:

using(StreamWriter writer = new StreamWriter(file,true))
{
    writer.WriteLine(username + "," + barcode + "," + DateTime.Now.ToString("yyyy-MM-dd HH.mm")+ "," + remarks);
    writer.Close();
}

或者,您可以在關閉后使writer對象無效。

嘗試使用writer.Flush(); writer.Close();之前writer.Close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM