0

當我打開一個用於解壓縮其內容的文件時,出現以下異常。當我在Windows資源管理器中選擇文件時,或者將鼠標懸停在顯示工具提示上時,會發生這種情況。使用File.OpenRead打開文件時發生System.IOException

System.IO.IOException was unhandled 
    Message=The process cannot access the file 'D:\Documents\AutoUnZip\Zips\MVCContrib.Extras.release.zip' because it is being used by another process. 
    Source=mscorlib 
    StackTrace: 
     at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) 
     at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) 
     at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) 
     at System.IO.File.OpenRead(String path) 
     at AutoUnzip.SelectFolderForm.w_Changed(Object sender, FileSystemEventArgs e) in D:\Projects\WindowsForms\AutoUnzip\AutoUnzip\SelectFolderForm.cs:line 37 
     at System.IO.FileSystemWatcher.OnCreated(FileSystemEventArgs e) 
     at System.IO.FileSystemWatcher.NotifyFileSystemEventArgs(Int32 action, String name) 
     at System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* overlappedPointer) 
     at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) 
    InnerException: 

有沒有一種方法只是等到文件不再被使用,然後讀取它?基本上我只是觀察任何新的zip文件的文件夾,解壓zip文件的內容,然後刪除它。

FileSystemWatcher watcher = new FileSystemWatcher("C:\\Path\\To\\Folder\\"); 
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName; 
watcher.Filter = "*.zip"; 
watcher.Created += new FileSystemEventHandler(w_Changed); 
// Begin watching. 
watcher.EnableRaisingEvents = true; 

事件處理程序:

void w_Changed(object sender, FileSystemEventArgs e) 
{ 
    // IOException on following line 
    using (ZipInputStream s = new ZipInputStream(File.OpenRead(e.FullPath))) 
    { 
     ... 
    } 
    // delete the zip file 
    File.Delete(e.FullPath); 
} 
+0

完整的源代碼示例工作任何有關它的最終解決方案? – Kiquenet 2013-07-30 05:59:19

回答

4

當您使用FileSystemWatcher時,這是完全正常的。它很可能是您獲取通知的文件正在由創建或修改文件的進程使用。您將不得不等到該過程停止使用它。你當然無法預測什麼時候發生。

一種通用的方法是將文件的路徑放入由定時器觸發的定期掃描的列表中。最終,您將可以訪問該文件。

+0

當另一個進程正在讀取文件時,你不能打開一個文件(用於閱讀)嗎? – SamWM 2010-08-27 14:05:26

+1

通常你可以,取決於應用程序。但是這不會產生FSW通知,因爲文件沒有被更改。 – 2010-08-27 14:11:37

1

也許this幫助。介紹幾種檢查文件是否正在使用的方法...

1

有時候,如果你只是複製反正錯誤拋出使用File.OpenRead其更改爲,而不是:

void w_Changed(object sender, FileSystemEventArgs e) 
{ 
    // IOException on following line 
    using (ZipInputStream s = new ZipInputStream(new System.IO.FileStream(e.FullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))) 
    { 
     ... 
    } 
    // delete the zip file 
    File.Delete(e.FullPath); 
} 
相關問題