API method to check if file exists in zip file?

Jun 29, 2009 at 3:32 PM

I have a zip file name, and a file to be added. Before I add the file, I would like to check if the file already exists in the zip file. Is there API method to do this? I understand that I could loop all the contant first. However, if there is one available, that would be nice.

Coordinator
Jun 29, 2009 at 5:03 PM

Two suggestions.

First, there's a string indexer on the entry collection. 

using (var zip = ZipFile.Read("archive.zip"))
{
  ZipEntry e = zip["NameOfEntry.txt"]; 
  if (e==null) 
  {
     // entry does not exist
  }
}

The indexer basically does what you would do - it enumerates the entries and checks to see if the filename matches. But it looks cleaner in app code. Keep in mind that you will match on the entire path in the archive of the filename. Check the doc for more on that.

The second thing is the ZipFile.UpdateFile() method. As the doc for the method says, it really should be called AddOrUpdateFile because it adds the file as an entry if it does not exist, and it updates the entry if it does exist. So you don't need to check simple existence before adding. You would still need to check if there is some other criterion that you'd like to use, like filesize, or attributes, or timestamp, to decide whether to add the file.