ZipArchive記憶體中檔案流壓縮
阿新 • • 發佈:2020-09-21
使用ZipArchive實現記憶體中檔案流壓縮
public interface IFileGenerator { string FileName { get; } //此處生成使用Byte陣列,使用流是一樣的 byte[] Generate(); } public sealed class FileGenerator : IFileGenerator { public string FileName => "File.zip"; public byte[] Generate() { var list = GetFileGeneratorChain(); using (MemoryStream ms = new MemoryStream()) { using (var zipArich = new ZipArchive(ms, ZipArchiveMode.Create, true)) { foreach (var item in list) { var bytes = item.Generate(); var entry = zipArich.CreateEntry(item.FileName); using (Stream stream = entry.Open()) { stream.Write(bytes, 0, bytes.Length); } } } return ms.GetBuffer(); } } private List<IFileGenerator> GetFileGeneratorChain() { //構造需要生成檔案的操作鏈 } }