Is there any way to check if a file is a valid zip file using System.IO.Compression functionality?
The solution: open the zip archive using the ZipFile.OpenRead() method and list all entries; if no exception happens, then the archive is valid.
For instance:
public static bool IsZipValid(string path)
{
try
{
using (var zipFile = ZipFile.OpenRead(path))
{
var entries = zipFile.Entries;
return true;
}
}
catch (InvalidDataException)
{
return false;
}
}
Extract ZIP file using ExtractToDirectory
and write code for invalid ZIP file within InvalidDataException
.
About "InvalidDataException" Exeption:-
The archive specified by sourceArchiveFileName is not a valid zip archive.
-or-
An archive entry was not found or was corrupt.
-or-
An archive entry was compressed by using a compression method that is not supported.
try
{
string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
catch (InvalidDataException ex)
{
//Handle invalid zip here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With