2015-03-31 45 views
0

有沒有辦法在閱讀之前等待此文件打開?正在讀取的文件將寫入相當多,不想讓這個錯誤繼續發生。我應該在嘗試閱讀之前延遲一段時間嗎?這是一個實時統計頁面,因此重新加載該頁面會發生很多。讀取可能正在更新的文件

System.IO.IOException: The process cannot access the file because it is being used by another process. 

回答

1

要測試文件被鎖定,您可以使用此功能:

protected virtual bool IsFileLocked(string filePath) 
    { 
     FileInfo file = new FileInfo(filePath); 
     FileStream stream = null; 

     try 
     { 
      stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); 
     } 
     catch (IOException) 
     { 
      //the file is unavailable because it is: 
      //still being written to 
      //or being processed by another thread 
      //or does not exist (has already been processed) 
      return true; 
     } 
     finally 
     { 
      if (stream != null) 
       stream.Close(); 
     } 

     //file is not locked 
     return false; 
    } 

通常它是不好用在你的正常邏輯異常,但在這種情況下,你可能不會有選擇。您可以每隔X秒調用一次,以檢查鎖。另一種方法是使用文件系統監視器對象來監視文件。如果不知道更多關於您的具體使用情況,很難說。

+1

請注意,您仍然有競爭條件 - 文件可以在此函數返回true和嘗試打開文件之間鎖定。你可能只是試圖打開它,並處理失敗,就好像這個函數返回false。 – Blorgbeard 2015-03-31 02:14:18