问题
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?
回答1:
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.
回答2:
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);
}
回答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);
}
}
回答4:
Move File.Delete outside using brackets using (ZipFile zip = ZipFile.Read(nextVersion + ".zip"))
来源:https://stackoverflow.com/questions/6577476/c-sharp-deleting-a-zip-file-after-unzipping