我正在尝试使用一个简单的演示文本文件创建一个ZIP存档,MemoryStream如下所示:
MemoryStream
using (var memoryStream = new MemoryStream()) using (var archive = new ZipArchive(memoryStream , ZipArchiveMode.Create)) { var demoFile = archive.CreateEntry("foo.txt"); using (var entryStream = demoFile.Open()) using (var streamWriter = new StreamWriter(entryStream)) { streamWriter.Write("Bar!"); } using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create)) { stream.CopyTo(fileStream); } }
如果运行此代码,则会创建存档文件本身,但不会创建 foo.txt 。
但是,如果我MemoryStream直接用文件流替换,则可以正确创建存档:
using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create)) using (var archive = new ZipArchive(fileStream, FileMode.Create)) { // ... }
是否可以使用MemoryStream而不创建ZIP存档FileStream?
FileStream
多亏了https://stackoverflow.com/a/12350106/222748,我得到了:
using (var memoryStream = new MemoryStream()) { using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) { var demoFile = archive.CreateEntry("foo.txt"); using (var entryStream = demoFile.Open()) using (var streamWriter = new StreamWriter(entryStream)) { streamWriter.Write("Bar!"); } } using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create)) { memoryStream.Seek(0, SeekOrigin.Begin); memoryStream.CopyTo(fileStream); } }
因此,我们需要在使用ZipArchive之前对其进行调用,这意味着将“ true”作为第三个参数传递给ZipArchive,以便我们在处理它后仍可以访问该流。