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

前端 未结 6 601
鱼传尺愫
鱼传尺愫 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:46

    You can use SharpZipLib among a variety of other libraries to achieve this.

    You can use the following code example to unzip to a MemoryStream, as shown on their wiki:

    using ICSharpCode.SharpZipLib.Zip;
    
    // Compresses the supplied memory stream, naming it as zipEntryName, into a zip,
    // which is returned as a memory stream or a byte array.
    //
    public MemoryStream CreateToMemoryStream(MemoryStream memStreamIn, string zipEntryName) {
    
        MemoryStream outputMemStream = new MemoryStream();
        ZipOutputStream zipStream = new ZipOutputStream(outputMemStream);
    
        zipStream.SetLevel(3); //0-9, 9 being the highest level of compression
    
        ZipEntry newEntry = new ZipEntry(zipEntryName);
        newEntry.DateTime = DateTime.Now;
    
        zipStream.PutNextEntry(newEntry);
    
        StreamUtils.Copy(memStreamIn, zipStream, new byte[4096]);
        zipStream.CloseEntry();
    
        zipStream.IsStreamOwner = false;    // False stops the Close also Closing the underlying stream.
        zipStream.Close();          // Must finish the ZipOutputStream before using outputMemStream.
    
        outputMemStream.Position = 0;
        return outputMemStream;
    
        // Alternative outputs:
        // ToArray is the cleaner and easiest to use correctly with the penalty of duplicating allocated memory.
        byte[] byteArrayOut = outputMemStream.ToArray();
    
        // GetBuffer returns a raw buffer raw and so you need to account for the true length yourself.
        byte[] byteArrayOut = outputMemStream.GetBuffer();
        long len = outputMemStream.Length;
    }
    

提交回复
热议问题