2

I am trying to verify that there is a file with a certain filename in a zip file. Is there a better way to do it than the following?

        using (ZipArchive archive = ZipFile.OpenRead(zipFilePath))
        {
            if (!archive.Entries.Any(e => e.Name.Equals(FileNameToCheckFor)))
            {
                // Throw an exception
            }

            foreach (ZipArchiveEntry file in archive.Entries)
            {
                // Do some processing. This is unrelated.
            }
        }
5
  • 1
    Maybe try codereview.stackexchange.com ? Commented May 7, 2013 at 0:07
  • Looks perfectly OK to me. Except I prefer to use var instead of the type name in the using for example: using (var archive = ...) Commented May 7, 2013 at 0:08
  • 1
    That seems pretty reasonable except that you're enumerating the list of entries twice. If there's a way to better organize your work you could probably avoid that. The importance of this is dependent on the size of the zip files as ripping through a 2PB Zip file twice is probably a bad idea... Commented May 7, 2013 at 0:08
  • 1
    @Chris surely the zip format has an index of files at the start.. Commented May 7, 2013 at 0:09
  • 1
    What about this instead? if (archive.GetEntry(ExportFileName) == null) Commented May 7, 2013 at 0:21

1 Answer 1

4

Since ZipArchive.GetEntry returns null if the entry does not exist, you could replace the lambda expression with:

 if (archive.GetEntry(FileNameToCheckFor) == null)
 {
      // Throw an exception
 }

This is slightly more concise, but that is not to imply anything incorrect about the original code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.