Erik Dahlen
Erik Dahlen

Reputation: 72

How to handle empty zip files with C# ZipFile

I have a program in C# which unzip files with ZipFile. It is normally working but if the zip file is empty it fails.

The code:

System.IO.Compression.ZipFile.ExtractToDirectory(fileName, dirName);

Is there a way to detect if the zip file is empty and delete it? (I do not want to delete the file if it fails and it is not empty.)

Upvotes: 0

Views: 1878

Answers (1)

Marian Simonca
Marian Simonca

Reputation: 1562

You can try this:

if (!string.IsNullOrEmpty(dirName) && Directory.Exists(dirName))
{
    try
    {
        System.IO.Compression.ZipFile.ExtractToDirectory(fileName, dirName);
    }
    catch (ArgumentException ex)
    {
        // file is empty (as we already checked for directory)
        File.Delete(fileName);
    }


    // OR

    if (new FileInfo(fileName).Length == 0)
    {
        // empty
        File.Delete(fileName);
    }
    else
    {
        System.IO.Compression.ZipFile.ExtractToDirectory(fileName, dirName);
    }
}

How to check if file is empty

Upvotes: 1

Related Questions