Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse encoding from WebClient Response?

Tags:

c#

.net

parsing

I get the Content-Type of a page trought a WebClient.ResponseHeaders. If I print it with:

client.ResponseHeaders["Content-Type"]

I get somethings like:

Content-Type: text/html; charset=UTF-8

so I want to get it (if there is). Else set a default one. This is my actual code:

var KeysParsed = HttpUtility.ParseQueryString(client.ResponseHeaders["Content-Type"].Replace(" ", "").Replace(";", "&"));
var charset = ((KeysParsed["charset"] != null) ? KeysParsed["charset"] : "UTF-8");

I don't know why, but it looks not so flexible. What can you suggest about?

like image 590
markzzz Avatar asked Oct 15 '13 07:10

markzzz


1 Answers

Why reinvent the wheel? See System.Net.Mime.ContentType:

var contentType = new ContentType(client.ResponseHeaders["Content-Type"]);
Console.WriteLine("{0} ({1})", contentType.MediaType, contentType.CharSet);

var charset = (contentType.CharSet ?? "UTF-8");
like image 168
Gene Avatar answered Nov 04 '22 10:11

Gene