Skip to main content
 首页 » 编程设计

c#之为什么我的 GZipStream 不可写

2024年02月23日14del

我的程序中有一些 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 类的限制?

请您参考如下方法:

您正在以错误的方式安装管道。修复:

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); 
}