C# – Compress / Decompress File with GZipStream

Compress

var compressedStream = new GZipStream(
              File.Create("file.dat"), CompressionMode.Compress); 
var formatter = new BinaryFormatter(); 
formatter.Serialize(compressedStream, data); 
compressedStream.Close(); 
compressedStream.Dispose(); 
formatter = null;

Decompress

var decompressedStream = new GZipStream(
               File.OpenRead("file.dat"), CompressionMode.Decompress);
var formatter = new BinaryFormatter();
string data = formatter.Deserialize(decompressedStream).ToString();
decompressedStream.Close();
decompressedStream.Dispose();
formatter = null;
//Data should be Stream object .. ways to define.
MemoryStream data = new MemoryStream();
or
StreamReader data = new StreamReader("file.txt");

//Tips:
Always before writing MemoryStream to another object/file, set positin index to 0

data.Position = 0;

Output Sample

Capture

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s