[英]File locked only if copy/paste, not if cut/paste
我正在監視文件夾中是否有新文件,並且當存在新文件時,我按以下方式讀取(並保存為txt):
FileStream file = File.Open(this.filePath, FileMode.Open, FileAccess.Read);
StreamReader reader = new System.IO.StreamReader(file);
string text = reader.ReadToEnd();
reader.Close();
如果我將源文件復制/粘貼到文件夾中,則會收到一個IOExcpetion,它告訴我該文件已被另一個進程使用。 如果我剪切/粘貼到文件夾中,則一切正常。 此外,如果我將文件從另一台計算機復制(也要剪切)/粘貼到受監視的文件夾中,也會發生鎖定問題。
您對發生的事情有想法嗎?
有一種更安全的方法來訪問文件以避免這種類型的鎖?
謝謝!
這是我要確保文件已完成復制或不被其他進程使用的小片段。
private bool FileUploadCompleted(string filename)
{
try
{
using (FileStream inputStream = File.Open(filename, FileMode.Open,
FileAccess.Read,
FileShare.None))
{
return true;
}
}
catch (IOException)
{
return false;
}
}
然后可以在流程邏輯之前實現
while (!FileUploadCompleted(filePath))
{
//if the file is in use it will enter here
//So you could sleep the thread here for a second or something to allow it some time
// Also you could add a retry count and if it goes past the allotted retries you
// can break the loop and send an email or log the file for manual processing or
// something like that
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.