创建ZIP档案库中的内存使用System.IO.Com pression库中、内存、档案、ZIP

2023-09-02 01:35:48 作者:话少又软萌的仙女

我试图创建一个使用一个ZIP压缩包有一个简单的演示文本文件中的的MemoryStream 如下:

I'm trying to create a ZIP archive with a simple demo text file using a MemoryStream as follows:

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:Temptest.zip", FileMode.Create))
    {
        stream.CopyTo(fileStream);
    }
}

如果我运行此code,归档文件本身创建,但的 foo.txt的的是没有的。

If I run this code, the archive file itself is created but foo.txt isn't.

不过,如果我取代的MemoryStream 直接与文件流,存档正确创建:

However, if I replace the MemoryStream directly with the file stream, the archive is created correctly:

using (var fileStream = new FileStream(@"C:Temptest.zip", FileMode.Create))
using (var archive = new ZipArchive(fileStream, FileMode.Create))
{
    // ...
}

是否有可能使用的MemoryStream 以创建无ZIP压缩包的的FileStream

Is it possible to use a MemoryStream to create the ZIP archive without the FileStream?

推荐答案

由于 http://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:Temptest.zip", FileMode.Create))
   {
      memoryStream.Seek(0, SeekOrigin.Begin);
      memoryStream.CopyTo(fileStream);
   }
}

因此​​,我们需要调用Dispose ZipArchive之前,我们可以使用它,这意味着通过真实作为第三个参数ZipArchive所以我们可以处理之后仍然可以访问流。

So we need to call dispose on ZipArchive before we can use it, which means passing 'true' as the third parameter to the ZipArchive so we can still access the stream after disposing it.