Reputation: 10701
I have some GZ compressed resources in my program and I need to be able to write them out to temporary files for use. I wrote the following function to write the files out and return true
on success or false
on failure. In addition, I've put a try/catch in there which shows a MessageBox
in the event of an error:
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;
}
I've put a comment on the line which throws the exception. If I put a breakpoint on that line and take a look inside the GZipStream
then I can see that it's not writeable (which is what's causing the problem).
Am I doing something wrong, or is this a limitation of the GZipStream
class?
Upvotes: 1
Views: 2682
Reputation: 941635
You are plumbing the pipes the wrong way. Fix:
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);
}
Upvotes: 5