我正在尝试使用多个文本文件创建ZIP存档,如下所示:
Dictionary<string,string> Values = new Dictionary<string,string>(); using (var memoryStream = new MemoryStream()) { string zip = @"C:\Temp\ZipFile.zip"; foreach (var item in Values) { using (var archive = new ZipArchive(memoryStream,ZipArchiveMode.Create,true)) { var file = archive.CreateEntry(item.Key + ".txt"); using (var entryStream = file.Open()) using (var streamWriter = new StreamWriter(entryStream)) { streamWriter.Write(item.Value); } } } using (var fileStream = new FileStream(zip,FileMode.Create)) { memoryStream.Seek(0,SeekOrigin.Begin); memoryStream.CopyTo(fileStream); } }
但是,ZIP仅使用最后一个文本文件创建,出了什么问题?
解决方法
您正在每次迭代时创建ZipArchive.交换foreach和使用应该解决它:
Dictionary<string,string>(); using (var memoryStream = new MemoryStream()) { string zip = @"C:\Temp\ZipFile.zip"; using (var archive = new ZipArchive(memoryStream,true)) { foreach (var item in Values) { var file = archive.CreateEntry(item.Key + ".txt"); using (var entryStream = file.Open()) using (var streamWriter = new StreamWriter(entryStream)) { streamWriter.Write(item.Value); } } } using (var fileStream = new FileStream(zip,SeekOrigin.Begin); memoryStream.CopyTo(fileStream); } }