Matthew Watson
Matthew Watson

Reputation: 109792

Any way to replicate the .Net Core DeflateStream.Flush() behaviour in .Net Framework?

Background

I want to use StreamJsonRpc as a replacement for WCF in a future .Net Core port of an application. Before porting the code to .Net Core, I want to update the existing code (which is .Net Framework 4.8) to use StreamJsonRpc.

Because the data written by StreamJsonRpc is large compared to the binary source data, and is extremely compressible, I want to use DeflateStream to compress it.

This leads on to the problem: The compression works with .Net Core, but it doesn't work with .Net Framework.

Why it doesn't work

Consider the following code:

var output   = new MemoryStream();
var deflater = new DeflateStream(output, CompressionMode.Compress, leaveOpen:true);
var data     = Encoding.UTF8.GetBytes("This is the data to be compressed");

deflater.Write(data, 0, data.Length);
deflater.Flush();

Console.WriteLine(output.Length); // 0 for .Net 4.8, >0 for .Net Core 3.1+

For .Net Core, this outputs a number greater than zero. For .Net Framework, this outputs zero.

I've instrumented StreamJsonRpc and I can see that it is calling Stream.Flush() after it writes a block of data, so I'm fairly sure that this is the problem.

The .Net Core implementation of DeflateStream.Flush() actually does flush, but the .Net Framework implementation does nothing.

My Question

Is there any way in .Net Framework 4.8 to flush a DeflateStream? If there is, I can write a wrapper class for DeflateStream that implements Stream.Flush() so that it actually flushes.

Other Notes

A bug was raised for this in October 2015, and it was fixed for .Net Core in December 2015.

Also, the documentation for DeflateStream.Flush() is incorrect.

For .Net Framework and .Net Core the header says:

The current implementation of this method has no functionality.

But under Remarks it says:

Flushes the internal buffer if the compression mode is set to Compress.

Clearly both those things can't be true, and the documentation should be different for .Net Core versus .Net Framework.

Upvotes: 1

Views: 212

Answers (0)

Related Questions