Question

I am reading an unzipped binary file from disk like this:

string fn = @"c:\\MyBinaryFile.DAT";
byte[] ba = File.ReadAllBytes(fn);
MemoryStream msReader = new MemoryStream(ba);

I now want to increase speed of I/O by using a zipped binary file. But how do I fit it into the above schema?

string fn = @"c:\\MyZippedBinaryFile.GZ";
//Put something here
byte[] ba = File.ReadAllBytes(fn);
//Or here
MemoryStream msReader = new MemoryStream(ba);

What is the best way to achieve this pls.

I need to end up with a MemoryStream as my next step is to deserialize it.

Was it helpful?

Solution

You'd have to use a GZipStream on the content of your file.

So basically it should be like this:

string fn = @"c:\\MyZippedBinaryFile.GZ";
byte[] ba = File.ReadAllBytes(fn);
using (MemoryStream msReader = new MemoryStream(ba))
using (GZipStream zipStream = new GZipStream(msReader, CompressionMode.Decompress))
{
    // Read from zipStream instead of msReader
}

To account for the valid comment by flindenberg, you can also open the file directly without having to read the entire file into memory first:

string fn = @"c:\\MyZippedBinaryFile.GZ";
using (FileStream stream = File.OpenRead(fn))
using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress))
{
    // Read from zipStream instead of stream
}

You need to end up with a memory stream? No problem:

string fn = @"c:\\MyZippedBinaryFile.GZ";
using (FileStream stream = File.OpenRead(fn))
using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress))
using (MemoryStream ms = new MemoryStream()
{
    zipStream.CopyTo(ms);
    ms.Seek(0, SeekOrigin.Begin); // don't forget to rewind the stream!

    // Read from ms
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top