Create Zip archive from multiple in memory files in C#

后端 未结 8 1893
情话喂你
情话喂你 2020-12-13 02:06

Is there a way to create a Zip archive that contains multiple files, when the files are currently in memory? The files I want to save are really just text only and are stor

8条回答
  •  离开以前
    2020-12-13 02:50

    I come across this problem, using the MSDN example I created this class:

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Text;  
    using System.IO.Packaging;  
    using System.IO;  
    
    public class ZipSticle  
    {  
        Package package;  
    
        public ZipSticle(Stream s)  
        {  
            package = ZipPackage.Open(s, FileMode.Create);  
        }  
    
        public void Add(Stream stream, string Name)  
        {  
            Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(Name, UriKind.Relative));  
            PackagePart packagePartDocument = package.CreatePart(partUriDocument, "");  
    
            CopyStream(stream, packagePartDocument.GetStream());  
            stream.Close();  
        }  
    
        private static void CopyStream(Stream source, Stream target)  
        {  
            const int bufSize = 0x1000;  
            byte[] buf = new byte[bufSize];  
            int bytesRead = 0;  
            while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)  
                target.Write(buf, 0, bytesRead);  
        }  
    
        public void Close()  
        {  
            package.Close();  
        }  
    }
    

    You can then use it like this:

    FileStream str = File.Open("MyAwesomeZip.zip", FileMode.Create);  
    ZipSticle zip = new ZipSticle(str);  
    
    zip.Add(File.OpenRead("C:/Users/C0BRA/SimpleFile.txt"), "Some directory/SimpleFile.txt");  
    zip.Add(File.OpenRead("C:/Users/C0BRA/Hurp.derp"), "hurp.Derp");  
    
    zip.Close();
    str.Close();
    

    You can pass a MemoryStream (or any Stream) to ZipSticle.Add such as:

    FileStream str = File.Open("MyAwesomeZip.zip", FileMode.Create);  
    ZipSticle zip = new ZipSticle(str);  
    
    byte[] fileinmem = new byte[1000];
    // Do stuff to FileInMemory
    MemoryStream memstr = new MemoryStream(fileinmem);
    zip.Add(memstr, "Some directory/SimpleFile.txt");
    
    memstr.Close();
    zip.Close();
    str.Close();
    

提交回复
热议问题