C# Deleting a .ZIP file after unzipping

家住魔仙堡 提交于 2019-12-07 06:50:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!