如何将此字符串解码为utf-8字符串?

时间:2013-04-05 14:30:05

标签: c# string utf-8 decode

我有这段代码:

string URL = "http://translate.google.com/m?hl=vi&sl=en&tl=vi&ie=UTF-8&prev=_m&q=song";
string s = "";
WebClient client = new WebClient();
client.Headers.Add("user-agent", "Mozilla/5.0 (SymbianOS/9.4; U; Series60/5.0 Nokia5800d-1/21.0.025; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413");
s = client.DownloadString(URL);

运行时,我收到一个格式为字符串的字符串:

danh tÆ°Ì€ buổi há»p để ca hát

到这个字符串:

danh từ buổi họp để ca hát

非常感谢:)

1 个答案:

答案 0 :(得分:1)

当获得表示字符串的byte[]时,您需要知道在获取之前使用了什么编码。

在这种情况下,它是UTF-8,因此将Encoding设置为WebClient会产生正确的字符串:

string URL = "http://translate.google.com/m?hl=vi&sl=en&tl=vi&ie=UTF-8&prev=_m&q=song";
string s = "";
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
client.Headers.Add("user-agent", "Mozilla/5.0 (SymbianOS/9.4; U; Series60/5.0 Nokia5800d-1/21.0.025; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413");
s = client.DownloadString(URL);