When you use GzipStream
or DeflateStream
from the System.IO.Compression
namespace, the Stream
you supply in the constructor will be written to for compression and read from in decompression.
Since you are trying to compress the data here, using the MemoryStream
is incorrect as you are not trying to compress to it, but rather use it as a data source. So your MemoryStream
should be the input Stream
and the FileStream
is your output.
I highly recommend you using MemoryStream
as a data source over the raw byte[]
because Stream
has a lot more versatility and application (FileStream
, NetworkStream
, CryptoStream
, etc.)
Here are some examples using the async
/await
pattern:
public static async Task CompressToFileAsync(byte[] buffer,
string outputFile)
{
using (var inputStream = new MemoryStream(buffer))
await CompressToFileAsync(inputStream, outputFile);
}
public static async Task CompressToFileAsync(Stream inputStream,
string outputFile)
{
using (var outputStream = File.Create(outputFile))
using (var gzip = new GZipStream(outputStream, CompressionMode.Compress))
{
await inputStream.CopyToAsync(gzip);
gzip.Close();
}
}
public static async Task<MemoryStream> DecompressFromFileAsync(string inputFile)
{
var outputStream = new MemoryStream();
using (var inputStream = File.Open(inputFile, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var gzip = new GZipStream(inputStream, CompressionMode.Decompress))
{
await gzip.CopyToAsync(outputStream);
gzip.Close();
inputStream.Close();
// After writing to the MemoryStream, the position will be the size
// of the decompressed file, we should reset it back to zero before returning.
outputStream.Position = 0;
return outputStream;
}
}
NOTE: Always call GzipStream.Close()
before you close the input or output Stream
. It does some final buffer flushing when closing/disposed and if the input or output is closed first it will throw an exception when it tries to do so. (This also applies to DeflateStream
)