13

I am using Ionic.Zip to extract ZipFile to memory stream with this method:

private MemoryStream GetReplayZipMemoryStream()
{
    MemoryStream zipMs = new MemoryStream();
    using (ZipFile zip = ZipFile.Read(myFile.zip))
    {
        foreach (ZipEntry zipEntry in zip)
        {
            if (zipEntry.FileName.StartsWith("Aligning") || zipEntry.FileName.StartsWith("Sensing"))
            {
                zipEntry.Extract(zipMs);
            }
        }
    }

    zipMs.Seek(0, SeekOrigin.Begin);
    return zipMs;
}

Once I am done extracting, I want to read the streams and get some of the entries based on the entry filename. How can I do that?

I tried by calling with the code below, but I get error on the ZipFile.Read(ms) which said:

Cannot read that as a ZipFile

Stream ms = GetReplayZipMemoryStream();
using (ZipFile zip = ZipFile.Read(ms))
{
    ZipEntry imageEntry = zip.Entries.First(x => x.FileName.EndsWith(".png"));
    using (Stream s = imageEntry.OpenReader())
    {
        var image = Image.FromStream(s);
        pictureBox1.Image = image;
    }
}

Thank you in advance for the help!

pbaris
  • 4,525
  • 5
  • 37
  • 61
Chocomelks
  • 131
  • 1
  • 1
  • 4
  • 5
    After you have done `.Extract()` the data (in the mem stream) is no longer zipped... You have a serie of concatenated uncompressed files. – H H Dec 22 '14 at 09:06
  • As Henk Holterman suggests, unless you are dealing with nested zip files, you should not be unzipping the files one more time in the second snippet. Could you provide a sample structure of the files you are trying to unzip? Alternatively I'd suggest you do all the filtering in the first loop and maybe even create the image there, in order not to write all the files you want to read, into a single stream. – Philip Atanassov Dec 22 '14 at 09:48
  • 2
    In addition to the observation Henk made, I'll suggest you not use Ionic.Zip to do this anyway. .NET now has the `ZipArchive` class, which provides built-in functionality to handle .zip files, and which IMHO is more convenient than the code you've got now. – Peter Duniho Dec 22 '14 at 18:22
  • 1
    @PeterDuniho Except it doesn't seem to handle encrypted zip files. If you don't need that I guess it's preferable to use that. – LJNielsenDk Apr 28 '15 at 13:11

1 Answers1

20

This may be little bit old question and late answer but I have did something to get the files as bytes collections and its file names like this

public static Dictionary<string, byte[]> Decompress(Stream targFileStream)
{
    Dictionary<string, byte[]> files = new Dictionary<string, byte[]>();

    using(ZipFile z = ZipFile.Read(targFileStream))
    {
        foreach (ZipEntry zEntry in z)
        {
            MemoryStream tempS = new MemoryStream();
            zEntry.Extract(tempS);

            files.Add(zEntry.FileName, tempS.ToArray());
        }
    }

    return files;
}
nramirez
  • 5,230
  • 2
  • 23
  • 39
Muhammad Nour
  • 2,109
  • 2
  • 17
  • 24