Create Zip archive from multiple in memory files in C#

后端 未结 8 1876
情话喂你
情话喂你 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 03:11

    This function should create a byte array from a stream of data: I've created a simple interface for handling files for simplicity

    public interface IHasDocumentProperties
    {
        byte[] Content { get; set; }
        string Name { get; set; }
    }
    
    public void CreateZipFileContent(string filePath, IEnumerable<IHasDocumentProperties> fileInfos)
    {    
        using (var memoryStream = new MemoryStream())
        {
            using (var zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
            {
                foreach(var fileInfo in fileInfos)
                {
                    var entry = zipArchive.CreateEntry(fileInfo.Name);
    
                    using (var entryStream = entry.Open())
                    {
                        entryStream.Write(fileInfo.Content, 0, fileInfo.Content.Length);
                    }                        
                }
            }
    
            using (var fileStream = new FileStream(filePath, FileMode.OpenOrCreate, System.IO.FileAccess.Write))
            {
                memoryStream.CopyTo(fileStream);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-13 03:12

    Note this answer is outdated; since .Net 4.5, the ZipArchive class allows zipping files in-memory. See johnny 5's answer below for how to use it.


    You could also do it a bit differently, using a Serializable object to store all strings

    [Serializable]
    public class MyStrings {
        public string Foo { get; set; }
        public string Bar { get; set; }
    }
    

    Then, you could serialize it into a stream to save it.
    To save on space you could use GZipStream (From System.IO.Compression) to compress it. (note: GZip is stream compression, not an archive of multiple files).

    That is, of course if what you need is actually to save data, and not zip a few files in a specific format for other software. Also, this would allow you to save many more types of data except strings.

    0 讨论(0)
提交回复
热议问题