我正在使用 System.IO.FileWatcher 來存檔目錄的傳入檔案。它在不同的檔案夾中創建新創建的檔案的副本。這是我的代碼:
private static async Task ArchiveFile(string filePath)
{
await Task.Run(async () =>
{
try
{
var fileName = DateTime.Now.ToString("yyMMdd-HHmmss_", null) Path.GetFileName(filePath);
using Stream source = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); // <- Exception is thrown here.
using Stream destination = new FileStream(Path.Combine(StringHelper.ArchivePath, fileName), FileMode.Create);
await source.CopyToAsync(destination);
Console.WriteLine($"Added file '{fileName}' to archive.");
source.Close();
source.Dispose();
destination.Close();
destination.Dispose();
}
catch(IOException e)
{
Console.WriteLine(e.Message);
}
});
}
即使出現例外“該行程無法訪問檔案‘C:/files/images/image.jpg’,因為它正被另一個行程使用”,一切都運行良好。在讀取檔案時總是拋出。
我希望這里也不例外,因為代碼作業得很好。
uj5u.com熱心網友回復:
可能是檔案尚未完全創建,例如檔案仍在復制/創建到您的源目的地。因此,當您嘗試從中讀取時,會出現檔案訪問錯誤。因此,您可以檢查是否可以讀取檔案,如果不能,請稍等片刻再試。
while (!CanReadFile(Path.Combine(filepath, filename)))
await Task.Delay(1000);
您的 CanReadFile 方法看起來像這樣:
private bool CanReadFile(string path)
{
try
{
using (var unused = File.OpenRead(path)) { }
}
catch (IOException ex)
{
if (IsFileLocked(ex))
{
return false;
}
}
return true;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/535902.html
標籤:C#。网例外复制
上一篇:帶兩個小數位的雙精度數
