[C#]WebClient.DownloadString 編碼錯誤產生不可辨視的文字

因為工作的關係,使用到 System.Net.WebClient.DownloadString這個方法;
結果接到的string中,中文字都顯示為亂碼。

問題:

因為工作的關係,使用到 System.Net.WebClient.DownloadString這個方法;

結果接到的string中,中文字都顯示為亂碼。


using System;
using System.Net;
using System.Text;

protected void Page_Load(object sender, EventArgs e)
{
  WebClient client = new WebClient();
  string result = client.DownloadString("http://tw.yahoo.com");
  // 編碼成UTF8 (有或沒有結果都相同)
  // result=Encoding.UTF8.GetString(Encoding.Default.GetBytes(result)); 
  Response.Write(result);
}

思考方向:

請參考http://www.cnblogs.com/ukessi/archive/2009/02/09/1386567.html

 

解決方法:

透過上篇文章後,確認是Encoding編碼問題;所以直接取得原本的Byte[],再手動進行相對應的解法。


using System;
using System.Net;
using System.Text;

protected void Page_Load(object sender, EventArgs e)
{
  WebClient client = new WebClient();
  byte[] bResult = client.DownloadData("http://tw.yahoo.com"); 
  string result = Encoding.UTF8.GetString(bResutlt);
  Response.Write(result);
}

4年後的補充:

感謝網友 Evan 的提醒,只要設定 WebClient Encoding即可。

請參考WebClient.Encoding 屬性


using System;
using System.Net;
using System.Text;

protected void Page_Load(object sender, EventArgs e)
{
  WebClient client = new WebClient();
   client.Encoding = Encoding.UTF8; // 設定Webclient.Encoding
   string result = client.DownloadString("http://tw.yahoo.com");
  Response.Write(result);
}