当我打开文件以解压缩其内容时,出现以下异常。当我在 Windows 资源管理器中选择文件或将鼠标悬停在显示工具提示的文件时会发生这种情况。
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);
}