Always Close DeflateStream Before Reading Results

November 24th 2007 .NET Framework

Is the code below correct? Will inputString and outputString be equal?

string inputString = "The text to compress and decompress";
byte[] inputArray = Encoding.UTF8.GetBytes(inputString);

MemoryStream stream = new MemoryStream();
DeflateStream compressionStream =
    new DeflateStream(stream, CompressionMode.Compress);
compressionStream.Write(inputArray, 0, inputArray.Length);
compressionStream.Flush();

stream.Position = 0;

DeflateStream decompressionStream =
    new DeflateStream(stream, CompressionMode.Decompress);
byte[] outputArray = new byte[inputArray.Length];
decompressionStream.Read(outputArray, 0, outputArray.Length);
string outputString = Encoding.UTF8.GetString(outputArray);

Console.WriteLine(outputString == inputString);
Console.ReadLine();

As it turns out, they won't. The reason for it being that compressionStream.Close() was not called before reading from stream started. Calling compressionStream.Flush() is not enough in this case. I haven't managed to find this documented anywhere but the example in the DeflateStream documentation does it correctly. You can find the fixed code below. Notice the additional last parameter in the first call to the DeflateStream constructor. Without it stream will also be closed when compressionStream gets closed.

string inputString = "The text to compress and decompress";
byte[] inputArray = Encoding.UTF8.GetBytes(inputString);

MemoryStream stream = new MemoryStream();
DeflateStream compressionStream =
    new DeflateStream(stream, CompressionMode.Compress, true);
compressionStream.Write(inputArray, 0, inputArray.Length);
compressionStream.Close();

stream.Position = 0;

DeflateStream decompressionStream =
    new DeflateStream(stream, CompressionMode.Decompress);
byte[] outputArray = new byte[inputArray.Length];
decompressionStream.Read(outputArray, 0, outputArray.Length);
string outputString = Encoding.UTF8.GetString(outputArray);

Console.WriteLine(outputString == inputString);
Console.ReadLine();

Thanks once again to my coworker for suggesting this when I was already running out of ideas.

Copyright
Creative Commons License