为什么我的 GZipStream 不可写?

Ozz*_*zah 1 c# compression gzip gzipstream

我的程序中有一些 GZ 压缩资源,我需要能够将它们写入临时文件以供使用。我编写了以下函数来写出文件并true在成功或false失败时返回。此外,我在其中放置了一个 try/catch,它MessageBox在发生错误时显示:

private static bool extractCompressedResource(byte[] resource, string path)
{
  try
  {
    using (MemoryStream ms = new MemoryStream(resource))
    {
      using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
      {
        using (GZipStream zs = new GZipStream(fs, CompressionMode.Decompress))
        {
          ms.CopyTo(zs); // Throws exception

          zs.Close();
          ms.Close();
        }
      }
    }
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message); // Stream is not writeable
    return false;
  }

  return true;
}
Run Code Online (Sandbox Code Playgroud)

我已经在引发异常的行上添加了注释。如果我在该行上放置一个断点并查看内部,GZipStream那么我可以看到它不可写(这就是导致问题的原因)。

我做错了什么,还是这是班级的限制GZipStream

Han*_*ant 5

您以错误的方式安装管道。使固定:

using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
using (MemoryStream ms = new MemoryStream(resource))
using (GZipStream zs = new GZipStream(ms, CompressionMode.Decompress))
{
   zs.CopyTo(fs);
}
Run Code Online (Sandbox Code Playgroud)