1
votes

I am trying to compress the output stream for my WCF service but for some reason when i compress and return the compressed stream i get empty response, although when i check on disk i see the compressed file does exist.

the method that does the compression:

public static Stream CompressResponseStream(FileStream stream,string filename, HttpContext context = null)
    {
        if (context == null)
            context = HttpContext.Current;

        string encodings = context.Request.Headers.Get("Accept-Encoding");

        if (!string.IsNullOrEmpty(encodings))
        {
            encodings = encodings.ToLowerInvariant();

            if (encodings.Contains("deflate"))
            {
                using (FileStream fs = File.OpenWrite($"{filename}.gzip"))
                using (var deflateStream = new DeflateStream(fs, CompressionMode.Compress))
                {
                    stream.CopyTo(deflateStream);
                    context.Response.AppendHeader("Content-Encoding", "deflate");
                    context.Response.AppendHeader("X-CompressResponseStream", "deflate");
                    fs.Flush();
                    return fs;
                }
            }
            else if (encodings.Contains("gzip"))
            {
                FileStream fs = new FileStream($"{filename}.gzip", FileMode.Create, FileAccess.ReadWrite);
                using (var gZipStream = new GZipStream(fs, CompressionMode.Compress))
                {
                    stream.CopyTo(gZipStream);
                    context.Response.AppendHeader("Content-Encoding", "gzip");
                    context.Response.AppendHeader("X-CompressResponseStream", "gzip");
                    fs.Flush();
                    return fs;
                }
            }
            else
            {
                context.Response.AppendHeader("X-CompressResponseStream", "no-known-accept");
            }
        }
        return stream;
    }
1
I found this post. I don't know if it might help you as I see you're returning a FileStream. A FileStream is not serializableRyan Gunn

1 Answers

0
votes

The problem was actually it didn't wrote it to disk until i closed the stream, so i had to close the stream and then to reopen file stream of the compressed file