How can I unzip a file to a .NET memory stream?

前端 未结 6 615
鱼传尺愫
鱼传尺愫 2020-12-14 00:16

I have files (from 3rd parties) that are being FTP\'d to a directory on our server. I download them and process them even \'x\' minutes. Works great.

Now, some of th

6条回答
  •  忘掉有多难
    2020-12-14 00:45

    Zip compression support is built in:

    using System.IO;
    using System.IO.Compression;
    // ^^^ requires a reference to System.IO.Compression.dll
    static class Program
    {
        const string path = ...
        static void Main()
        {
            using(var file = File.OpenRead(path))
            using(var zip = new ZipArchive(file, ZipArchiveMode.Read))
            {
                foreach(var entry in zip.Entries)
                {
                    using(var stream = entry.Open())
                    {
                        // do whatever we want with stream
                        // ...
                    }
                }
            }
        }
    }
    

    Normally you should avoid copying it into another stream - just use it "as is", however, if you absolutely need it in a MemoryStream, you could do:

    using(var ms = new MemoryStream())
    {
        stream.CopyTo(ms);
        ms.Position = 0; // rewind
        // do something with ms
    }
    

提交回复
热议问题