[英]Is there any way to check file readability before trying to read it in FileSystemWatcher.Changed event?
我使用FileSystemWatcher來監視某些文件夾的更改。 當它觸發文件更改事件時,我需要讀取該文件並更新一些內容。 問題是,當觸發此事件時,即使以這種方式仍然禁止目標文件讀取FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
是否還有其他事件通知文件已結束更改? 或者無論如何要創建一些等待文件讀取能力的服務員通過一些標准方式(WinAPI等)。 或者循環嘗試catch是唯一的選擇?
如果文件流可用,則應使用以下幫助程序方法返回文件流。
public static FileStream WaitForFile(string fullName)
{
FileStream fs = null;
int numTries = 0;
while (true)
{
++numTries;
try
{
//try to open the file
fs = new FileStream(fullName, FileMode.Open, FileAccess.Read, FileShare.None, 100);
fs.ReadByte();//if it's open, you can read it
fs.Seek(0, SeekOrigin.Begin);//Since you read one byte, you should move the cursor position to the begining.
break;
}
catch (Exception ex)
{
if (numTries > 10)//try 10 times
{
return fs;//Or you can throw exception
}
System.Threading.Thread.Sleep(10000);//wait
}
}
return fs;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.