Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharpZipLib Examine and select contents of a ZIP file

I am using SharpZipLib in a project and am wondering if it is possible to use it to look inside a zip file, and if one of the files within has a data modified in a range I am searching for then to pick that file out and copy it to a new directory? Does anybody know id this is possible?

like image 914
DukeOfMarmalade Avatar asked Nov 29 '11 15:11

DukeOfMarmalade


1 Answers

Yes, it is possible to enumerate the files of a zip file using SharpZipLib. You can also pick files out of the zip file and copy those files to a directory on your disk.

Here is a small example:

using (var fs = new FileStream(@"c:\temp\test.zip", FileMode.Open, FileAccess.Read))
{
  using (var zf = new ZipFile(fs))
  {
    foreach (ZipEntry ze in zf)
    {
      if (ze.IsDirectory)
        continue;

      Console.Out.WriteLine(ze.Name);            

      using (Stream s = zf.GetInputStream(ze))
      {
        byte[] buf = new byte[4096];
        // Analyze file in memory using MemoryStream.
        using (MemoryStream ms = new MemoryStream())
        {
          StreamUtils.Copy(s, ms, buf);
        }
        // Uncomment the following lines to store the file
        // on disk.
        /*using (FileStream fs = File.Create(@"c:\temp\uncompress_" + ze.Name))
        {
          StreamUtils.Copy(s, fs, buf);
        }*/
      }            
    }
  }
}

In the example above I use a MemoryStream to store the ZipEntry in memory (for further analysis). You could also store the ZipEntry (if it meets certain criteria) on disk.

Hope, this helps.

like image 83
Hans Avatar answered Sep 24 '22 04:09

Hans