Convertir le jeu de caractères d'une page web téléchargée

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);

}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Add comment


(Will show your Gravatar icon)  

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

November 21. 2008 14:42