1

我的程序中有一些 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;
}

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

我做错了什么,或者这是GZipStream课程的限制?

4

1 回答 1

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);
}
于 2011-11-17T01:52:33.777 回答