Welcome to the navigation

Elit, voluptate tempor officia reprehenderit id consectetur ut commodo anim esse occaecat excepteur amet, incididunt sunt ipsum quis in qui pariatur, sint eu est veniam. Exercitation adipisicing enim ut mollit ipsum ullamco duis do voluptate laboris eiusmod in velit aute ut in dolor veniam, ut nostrud lorem consequat, pariatur, amet

Yeah, this will be replaced... But please enjoy the search!

Compress a file using GZip and convert it to Base64 - and back - using C#

Sometimes you want to store a file in a database or even transfer stuff over the Internet through different protocols, maybe even to other platforms. In many of these cases the traditional methods simply wont do. Storing files in databases is usually made by sending the file as a blob to the database and it usually works out pretty good to, but in some cases you simply want a different structure. I often tend to end up in projects with several platforms and languages, this means XML or similar languages like JSON. Anyway binary data is out, you need a different way to transfer or store files. When it comes to files I recommend using GZip compression which is shipped as a standard with .NET.

If you are looking for a less complex compresson you should use gzdeflate and gzinflate.

Compressing a file

string fileName = @"c:\test.pdf";
byte[] file = File.ReadAllBytes(fileName);

// Compress
byte[] compress = Compress(file);

public static byte[] Compress(byte[] data)
{ using (var compressedStream = new MemoryStream()) using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress)) { zipStream.Write(data, 0, data.Length); zipStream.Close(); return compressedStream.ToArray(); } }

Encode the byte array

string encoded = base64_encode(compress);

public string base64_encode(byte[] data)
{ if (data == null) throw new ArgumentNullException("data"); return Convert.ToBase64String(data); }

The contents of "encoded" is your file but compressed and base64 encoded. You can take this string and send it through any protocol allowing strings. If we print the encoded string it looks something like this

Decode and Decompress

// Decode and decompress
byte[] decoded = base64_decode(encoded);
byte[] decompressed = Decompress(decoded);
File.WriteAllBytes(@"c:\out.pdf", decompressed);

public static byte[] base64_decode(string encodedData) { byte[] encodedDataAsBytes = Convert.FromBase64String(encodedData); return encodedDataAsBytes; }

public static byte[] Decompress(byte[] data) { using (var compressedStream = new MemoryStream(data)) using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress)) using (var resultStream = new MemoryStream()) { var buffer = new byte[4096]; int read; while ((read = zipStream.Read(buffer, 0, buffer.Length)) > 0) { resultStream.Write(buffer, 0, read); } return resultStream.ToArray(); } }