我的程序中有一些GZ压缩资源,我需要能够将它们写出到临时文件以供使用。我编写了下列函数来写出文件,并成功返回true
或失败时返回false
。另外,我已经把一个try/catch在那里它显示了一个MessageBox
在一个错误的事件:为什么我的GZipStream不可写入?
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
类的限制吗?
无需关闭流在一个“使用”块,它们将自动当它们被布置 – musefan
也关闭,作为书面,GZipStream将GZipStream设置当处置的FileStream的。对于OP也是如此:在处理之前,您没有在示例中明确调用.Flush在您的示例中的'zs'和'fs',我们发现了一些问题。 – Joe