0

Using ZipArchive how can I check if a file is a valid zip archive?

I am currently catching an InvalidDataException when attempting to enumerate through the zip entries but I don't believe that this is the best way to do this:

public static bool IsCompressed(this HttpPostedFile postedFile)
{
    try
    {
        var entries = new ZipArchive(postedFile.InputStream).Entries;
        return true;
    }
    catch (InvalidDataException)
    {
        return false;
    }
}
Dave New
  • 38,496
  • 59
  • 215
  • 394
  • 2
    What's wrong with it? Does it not do what you want? If it does, then why change it? – Oskar Kjellin May 16 '13 at 12:12
  • Because exceptions should not be used to change the flow of a program as part of ordinary execution. Exceptions should only be used to report and handle exceptional application error conditions. If I must use it, then I will. I was just wondering if there is another/better way of validating. – Dave New May 16 '13 at 12:17
  • I know that it shouldn't. But if it makes your code clean, readable and functional, then why not? "Should not" is in my opinion not argument. Spend your time writing new code or fixing broken code. Don't fix something that isn't broken – Oskar Kjellin May 16 '13 at 12:20
  • @davenewza Having a malformed zip file should be an exceptional case. If you're just receiving some random file and want to know whether it's a zip archive, I'd recommend checking the file header **before** instantiating the `ZipArchive` object. http://en.wikipedia.org/wiki/Magic_number_(programming)#Examples – Kevin Gosse May 16 '13 at 12:21

0 Answers0