Search code examples
c#sslgzipgzipstreamsslstream

C# SslStream with GZipStream


Is it possible to use GZipStream passing an SslStream in C#? i.e. can you do


GZipStream stream = new GZipStream(sslStream, CompressionMode.Compress);
stream.Write(...);

...

GZipStream stream = new GZipStream(sslStream, CompressionMode.Decompress);
stream.Read(...);

If this is possible, is the SslStream still in a useable state after this or should it be closed?

Thanks.


Solution

  • I can't think why not; the SSL stream will just be given bytes, but that is what it expected anyway. The important thing is to close the GZipStream properly, as even Flush() doesn't always really flush (due to having to keep a running buffer for compression). So:

    using(GZipStream stream = new GZipStream(sslStream, CompressionMode.Compress)) {
        stream.Write(...);
        stream.Close(); // arguably overkill; the Dispose() from "using" should be enough
    }
    

    I'm also assuming that you aren't reading and writing to the same SSL stream (i.e. that is two separate examples, not one example), as that doesn't sound likely to work.