When I was studying for the 70-536 exam, I concentrated heavily on streams as it was a good portion of the exam. One stream that stuck in my mind the most was the GZipStream which encompasses the industry standard for lossless file compression and decompression in the GZip format.
As I always did during the reading process was to whip up little examples of using each technology. I decided to create a little example of how to use the GZipStream in a few lines of code while compressing a known document. I took the C# 2.0 Specification document and compressed it using the GZipStream.
Below is the code I used:
static void Main(string[] args)
{
{
// Get bytes from input stream
FileStream inFileStream = new FileStream(Path.Combine(Environment.CurrentDirectory, "C# Language Specification 2.0.doc"), FileMode.Open);
byte[] buffer = new byte[inFileStream.Length];
inFileStream.Read(buffer, 0, buffer.Length);
inFileStream.Close();
FileStream inFileStream = new FileStream(Path.Combine(Environment.CurrentDirectory, "C# Language Specification 2.0.doc"), FileMode.Open);
byte[] buffer = new byte[inFileStream.Length];
inFileStream.Read(buffer, 0, buffer.Length);
inFileStream.Close();
// Create GZip file stream and compress input bytes
FileStream outFileStream = new FileStream(Path.Combine(Environment.CurrentDirectory, "C# Language Specification 2.0.doc.gzip"), FileMode.Create);
GZipStream compressedStream = new GZipStream(outFileStream, CompressionMode.Compress);
compressedStream.Write(buffer, 0, buffer.Length);
compressedStream.Close();
outFileStream.Close();
}
GZipStream compressedStream = new GZipStream(outFileStream, CompressionMode.Compress);
compressedStream.Write(buffer, 0, buffer.Length);
compressedStream.Close();
outFileStream.Close();
}
As you can see, the code above is very simple. What this does is read in the C# Specification 2.0 doc and get the bytes, then read it in to a new compressed filestream. This creates a file called C# Specification 2.0.doc.gzip.
You can verify the results of the operation, as it reduced the size of the document from 861KB to 271KB. If you open the gzip archive with an appropriate viewer, such as WinRAR, or 7-Zip (my favorite). Once you open it, you will notice that indeed it has the document in there nicely compacted.
Below is a picture of what it should look like:
Like I said above, there really wasn't much to this except for experimentation purposes. There are other examples on MSDN worth looking into such as one located here.
No comments:
Post a Comment