Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating zip files using System.IO.Compression

Tags:

c#

.net

zip

Is there any way to check if a file is a valid zip file using System.IO.Compression functionality?

like image 582
user626528 Avatar asked Aug 16 '16 09:08

user626528


2 Answers

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;
        }
    }
like image 140
user626528 Avatar answered Nov 09 '22 07:11

user626528


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
        }
like image 21
Jitendra.Suthar Avatar answered Nov 09 '22 07:11

Jitendra.Suthar