Cannot Delete Zip file Created by SharpZipLib (FastZip)
-
19-08-2019 - |
Question
I'm creating a zip file using the class FastZip from SharpZipLib and once I after I close the program, I cannot delete the file because:
"Cannot delete zip.zip: It is being used by another person or program. Close any programs that might be using the file and try again."
The code that is generating the file is simply this:
fZip.CreateEmptyDirectories = true;
fZip.CreateZip(filesPath + "\\" + this.zipName, filesPath, false, this.zipFilter);
I tried using:
using (FastZip fZip = new FastZip())
{
try
{
fZip.CreateEmptyDirectories = true;
fZip.CreateZip(filesPath + "\\" + this.zipName, filesPath, false, this.zipFilter);
}
catch (Exception)
{
}
}
But it doesn't convert to iDisposable
Solution
Perhaps antivirus is busy checking the file? If not, then get a program that can tell you which programs have files open.
You can look at:
OTHER TIPS
It looks like it may be a bug with SharpZipLib. The FastZip.CreateZip method has three overloads and two of them create use File.Create such as:
CreateZip(File.Create(zipFileName), // ...
It seems it does not close the stream, so you may be better off using:
string zipFileName = System.IO.Path.Combine(filesPath, this.zipName);
using (Stream stream = File.Create(zipFileName))
{
fZip.CreateZip(stream, filesPath, false, this.zipFilter, null);
stream.Close();
}
Technically you shouldn't need to call Close in the using block, but I like to be explicit about it.
I actually just solved this problem myself. Turns out that it wasn't SharpZipLib/FastZip. I was sending an email via System.Net.Mail and had attached the FastZipped file as an attachment to that email. When I tried to delete the attached file, I ran into the error which you received. Turns out that all I had to do was call MailMessage.Dispose() after sending the email.
Take a look at any other items within your code which might be holding a lock on the file; try to dispose() or close() those items if possible.
I'm not familier with the FastZip API (so this is just a punt) but do you need to close the archive with something like fZip.Close();
I would have thought that closing the program would have done the same thing but just a guess.
Make sure you CLOSE the SharpZipLib stream after you're finished with it, you can do this by wrapping the construction of it inside a "using" statement...
using(Stream s = new SharpZipLibStream())
{
/*...do stuff, zip stuff.../
}