Using SharpZipLib to unzip specific files?

后端 未结 4 997
你的背包
你的背包 2020-12-04 21:57

I\'m trying to use SharpZipLib to pull specified files from a zip archive. All of the examples I\'ve seen always expect that you want to unzip the entire zip, and do somethi

4条回答
  •  再見小時候
    2020-12-04 22:09

    Note - this answer suggests an alternative to SharpZipLib


    DotNetZip has a string indexer on the ZipFile class to make this really easy.

     using (ZipFile zip = ZipFile.Read(sourcePath)
     {
       zip["NameOfFileToUnzip.txt"].Extract();
     }
    

    You don't need to fiddle with inputstreams and outputstreams and so on, just to extract a file. On the other hand if you want the stream, you can get it:

     using (ZipFile zip = ZipFile.Read(sourcePath)
     {
       Stream s = zip["NameOfFileToUnzip.txt"].OpenReader();
       // fiddle with stream here
     }
    

    You can also do wildcard extractions.

     using (ZipFile zip = ZipFile.Read(sourcePath)
     {
         // extract all XML files in the archive
         zip.ExtractSelectedEntries("*.xml");
     }
    

    There are overloads to specify overwrite/no-overwrite, different target directories, etc. You can also extract based on criteria other than the filename. For example, extract all files newer than January 15, 2009:

         // extract all files modified after 15 Jan 2009
         zip.ExtractSelectedEntries("mtime > 2009-01-15");
    

    And you can combine criteria:

         // extract all files that are modified after 15 Jan 2009) AND  larger than 1mb
         zip.ExtractSelectedEntries("mtime > 2009-01-15 and size > 1mb");
    
         // extract all XML files that are modified after 15 Jan 2009) AND  larger than 1mb
         zip.ExtractSelectedEntries("name = *.xml and mtime > 2009-01-15 and size > 1mb");
    

    You don't have to extract the files that you select. You can just select them and then make decisions on whether to extract or not.

        using (ZipFile zip1 = ZipFile.Read(ZipFileName))
        {
            var PhotoShopFiles = zip1.SelectEntries("*.psd");
            // the selection is just an ICollection
            foreach (ZipEntry e in PhotoShopFiles)
            {
                // examine metadata here, make decision on extraction
                e.Extract();
            }
        }
    

提交回复
热议问题