Suite a mon précédent post sur l'extraction des liens dans une page, je me suis penché sur le probleme de gérer les différents encodages des pages analysées. Voici un snippet de code pour convertir dans un jeu de caractere choisi les données de la page, en tenant compte du codepage du site.
private string DownloadWebPage(string uri, System.Text.Encoding targetCodePage)
{
WebClient client = new WebClient();
System.Text.Encoding source;
byte[] pageData = client.DownloadData(uri);
string contentType = client.ResponseHeaders["content-type"];
Regex re = new Regex(";.*charset=(?.*)", RegexOptions.IgnoreCase);
Match match = re.Match(contentType);
if (match.Success)
source = Encoding.GetEncoding(match.Groups["codepage"].Value);
else
source = client.Encoding;
byte[] localData;
if (targetCodePage.Equals(source))
localData = pageData;
else
localData = System.Text.Encoding.Convert(source, targetCodePage, pageData);
return targetCodePage.GetString(localData);
}