Create Zip archive from multiple in memory files in C#

后端 未结 8 1874
情话喂你
情话喂你 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 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);
            }
        }
    }
    

提交回复
热议问题