當我執行下面的代碼時,出現普通異常The process cannot access the file *filePath* because it is being used by another process
。進程無法訪問該文件,因爲它正在被另一個進程使用
允許此線程等待它可以安全地訪問此文件的最有效方法是什麼?
假設:
- 文件剛剛被我創建的,所以這是不可能的另一個應用程序正在訪問它。
- 來自我的應用程序的多個線程可能試圖運行此代碼以將文本附加到該文件。
:
using (var fs = File.Open(filePath, FileMode.Append)) //Exception here
{
using (var sw = new StreamWriter(fs))
{
sw.WriteLine(text);
}
}
到目前爲止,我想出了是下面的最好的。這樣做有什麼缺點嗎?
private static void WriteToFile(string filePath, string text, int retries)
{
const int maxRetries = 10;
try
{
using (var fs = File.Open(filePath, FileMode.Append))
{
using (var sw = new StreamWriter(fs))
{
sw.WriteLine(text);
}
}
}
catch (IOException)
{
if (retries < maxRetries)
{
Thread.Sleep(1);
WriteToFile(filePath, text, retries + 1);
}
else
{
throw new Exception("Max retries reached.");
}
}
}
在我的情況下,這仍然拋出相同的異常。我想念什麼? – 2015-07-27 13:27:33
@MauroBilotti:你確定,你的過程是唯一一個訪問文件? – Oliver 2015-07-27 13:29:48
奧利弗,它的工作原理是,我必須在'閱讀'模式下更改文件訪問權限,因爲我是以這種方式打開它。謝謝!我會鼓勵你 – 2015-07-27 13:44:04