6

I am using the Ionic.Zip.dll from the DotNetZip library and I'm trying to delete the ZIP file after it finishes unzipping, but I can't manage to do it.

Here is the code I have currently:

    using (ZipFile zip = ZipFile.Read(nextVersion + ".zip"))
{
    zip.ExtractAll(Directory.GetCurrentDirectory(), ExtractExistingFileAction.OverwriteSilently);

    try
    {
        File.Delete(nextVersion + ".zip");
    }
    catch (Exception)
    {
        MessageBox.Show("Could not delete ZIP!");
        Environment.Exit(1);
    }
}

What am I doing wrong here?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Alan
  • 87
  • 1
  • 1
  • 5

4 Answers4

9

You are getting the exception because the file is still open when you try to delete. Move the File.Delete to after the using block.

Richard Schneider
  • 34,944
  • 9
  • 57
  • 73
4

Try this?

try {
    using (ZipFile zip = ZipFile.Read(nextVersion + ".zip"))
    {
        zip.ExtractAll(Directory.GetCurrentDirectory(), ExtractExistingFileAction.OverwriteSilently);
    }
    File.Delete(nextVersion + ".zip");
}
catch (Exception) {
   MessageBox.Show("Could not delete ZIP!");
   Environment.Exit(1);
}
Naeem Sarfraz
  • 7,360
  • 5
  • 37
  • 63
3

Yes! I have the same answer as Richard Schneider. The zip file is still accessed by current thread, you have to close it first.

Try this

 using (ZipFile zip = ZipFile.Read(nextVersion + ".zip"))
            {
                zip.ExtractAll(Directory.GetCurrentDirectory(), ExtractExistingFileAction.OverwriteSilently);
                zip.Dispose();
                try
                {
                    File.Delete(nextVersion + ".zip");
                }
                catch (Exception)
                {
                    MessageBox.Show("Could not delete ZIP!");
                    Environment.Exit(1);
                }
            }
Tran Dang
  • 158
  • 5
0

Move File.Delete outside using brackets using (ZipFile zip = ZipFile.Read(nextVersion + ".zip"))

Abhijit
  • 105
  • 2
  • 9