2015-04-24 19 views
0

觀察File.GetCreationTime返回的Win32錯誤18 - 沒有更多文件

我有我已被告知正在運行了好幾年沒有問題,但最近已開始與一個奇怪的錯誤而崩潰的應用程序。代碼本身是相當簡單:

private void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e) 
{ 
    //Make sure it's not a folder that was modified 
    if (!Directory.Exists(e.FullPath)) 
    { 
     var creationTime = File.GetCreationTime(e.FullPath); 

     // Rest of the code here... 

然而,調用GetCreationTime,偶爾會引發異常,產生以下調用堆棧:

 
System.IO.IOException: There are no more files. 
    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) 
    at System.IO.File.GetCreationTimeUtc(String path) 
    at MyClass.fileSystemWatcher_Changed(Object sender, FileSystemEventArgs e) 
    at ... 

現在,我已經擦上GetCreationTimeMSDN documentation以及因爲使用ILSpy仔細檢查了代碼,並得出以下結論:

System.IO.File.GetCreationTime方法是對等效Win API集來電,包括GetFileAttributesExFindFirstFile。我不相信任何這些調用應該返回錯誤18.事實上,.NET實現有一個特定的硬編碼錯誤,它期望(2,3和21),並在大多數情況下只會吃掉例外,並返回DateTime.MinValue

問題

什麼導致這個例外,什麼是最好的糾正措施,以代碼來避免或預防呢? (現在,我在塊的周圍添加了try catch以僅記錄事件並忽略。)

這是Windows操作系統的問題嗎(類似於這個舊的KB article)?

+0

的文件添加和正在觀看的文件夾中刪除多久? – vcsjones

+0

你打電話給**文件**。GetCreationTime在一個目錄 –

+0

@PanagiotisKanavos它看起來像一個文件給我。這是檢查,以確保它*不是一個目錄。 *!* Directory.Exists – vcsjones

回答

0

您的代碼正在檢查路徑是否是而不是目錄。一個false響應並不意味着該路徑指向一個文件,它也可以表示這個名字沒有任何內容。

使用File.Exists代替:

if (FileExists(e.FullPath)) 
{ 
    var creationTime = File.GetCreationTime(e.FullPath); 
+0

但是,在目錄路徑或不存在的文件上調用'File.GetCreationTime'不應引發異常。看到這個小提琴:https://dotnetfiddle.net/QTIBzd – nicholas

相關問題