Getting the Content-Encoding header in C#
Recently I needed to get the Content-Encoding header within a C# application.After trying to figure out why the response was empty, and after reading different community posts where other users had the same problem and none of the suggestions seem to solve it, I’ve decided to post my solution for further use.
Let’s take a look at how things stand.
The Problem
public static string GetEncoding(string url)
{
HttpWebRequest request;
HttpWebResponse response;
string result = null;
try
{
request = (HttpWebRequest)WebRequest.Create(url);
response = (HttpWebResponse)request.GetResponse();
result = response.ContentEncoding;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return result;
}
static void Main(string[] args)
{
Console.WriteLine(GetEncoding("http://microsoft.com"));
}
We declare a HttpWebRequest and HttpWebResponse object, we create the request, get the response but when we try to see the ContentEncoding return message, it’s always empty, null.

The solution
public static string GetEncoding(string url)
{
HttpWebRequest request;
HttpWebResponse response;
string result = null;
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
response = (HttpWebResponse)request.GetResponse();
result = response.ContentEncoding;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return result;
}
static void Main(string[] args)
{
Console.WriteLine(GetEncoding("http://microsoft.com"));
}
The solution is to implicitly set the Accept-Encoding header to be sent with the request.We can do this either by using HttpRequestHeader.AcceptEncoding or by declaring as such:
request.Headers.Add("Accept-Encoding", "gzip,deflate");
Either way, it does the same thing.Now, after sending the Accept-Encoding header, we get the right response in the response.ContentEncoding.

I hope this article solved your issue.Stay tuned for more C# helpful articles.
Thank you for sharing!
Good information, keep working man. I like your website. Cheers~~~~
You’re more than welcome. Thanks for visiting!