创建ZIP档案库中的内存使用System.IO.Com pression [英] Creating a ZIP Archive in Memory Using System.IO.Compression

查看:160
本文介绍了创建ZIP档案库中的内存使用System.IO.Com pression的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个使用一个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:\Temp\test.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:\Temp\test.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:\Temp\test.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.

这篇关于创建ZIP档案库中的内存使用System.IO.Com pression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆