0

内容を解凍するためにファイルを開くと、次の例外が発生します。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);
}
4

3 に答える 3

4

FileSystemWatcher を使用する場合、これはまったく正常です。通知を受け取ったファイルは、そのファイルを作成または変更したプロセスによって使用されている可能性が非常に高いです。プロセスがそれを使用しなくなるまで待つ必要があります。もちろん、それがいつ起こるかを予測することはできません。

一般的なアプローチは、タイマーによってトリガーされ、定期的にスキャンするリストにファイルへのパスを配置することです。最終的に、ファイルにアクセスできるようになります。

于 2010-08-26T18:20:58.173 に答える
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); 
} 
于 2012-06-24T03:49:51.160 に答える
0

たぶんこれが役立ちます。ファイルが使用されているかどうかを確認するいくつかの方法について説明します...

于 2010-08-26T17:52:41.830 に答える