简体   繁体   中英

Displaying the contents of a Zip archive in WinRT

I want to iterate through the contents of a zipped archive and, where the contents are readable, display them. I can do this for text based files, but can't seem to work out how to pull out binary data from things like images. Here's what I have:

var zipArchive = new System.IO.Compression.ZipArchive(stream);

foreach (var entry in zipArchive.Entries)
{
    using (var entryStream = entry.Open())
    {
        if (IsFileBinary(entry.Name))
        {
            using (BinaryReader br = new BinaryReader(entryStream))
            {
                //var fileSize = await reader.LoadAsync((uint)entryStream.Length);
                var fileSize = br.BaseStream.Length;
                byte[] read = br.ReadBytes((int)fileSize);

                binaryContent = read;

I can see inside the zip file, but calls to Length result in an OperationNotSupported error. Also, given that I'm getting a long and then having to cast to an integer, it feels like I'm missing something quite fundamental about how this should work.

I think the stream will decompress the data as it is read, which means that the stream cannot know the decompressed length. Calling entry.Length should return the correct size value that you can use. You can also call entry.CompressedLength to get the compressed size.

Just copy the stream into a file or another stream:

using (var fs = await file.OpenStreamForWriteAsync())
{
    using (var src = entry.Open())
    {
        var buffLen = 1024;
        var buff = new byte[buffLen];
        int read;
        while ((read = await src.ReadAsync(buff, 0, buffLen)) > 0)
        {
            await fs.WriteAsync(buff, 0, read);
            await fs.FlushAsync();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM