Is there a quick way to uncompress gzip response downloaded with WebClient.DownloadString() method? Do you have any suggestions on how to handle gzip responses with WebClient?
Asked
Active
Viewed 1.8k times
1 Answers
76
The easiest way to do this is to use the built in automatic decompression with the HttpWebRequest
class.
var request = (HttpWebRequest)HttpWebRequest.Create("http://stackoverflow.com");
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
To do this with a WebClient
you have to make your own class derived from WebClient
and override the GetWebRequest()
method.
public class GZipWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
return request;
}
}
Also see this SO thread: Does .NET's HttpWebResponse uncompress automatically GZiped and Deflated responses?

Community
- 1
- 1

BrokenGlass
- 158,293
- 28
- 286
- 335
-
2is it not necessary to specify the acceptencoding header for the derived webclient class? – user3791372 Jan 15 '17 at 14:50