WebClient.DownloadString 使用错误的编码

Lie*_*ero 5 .net c# webclient character-encoding

我正在使用 webclient 从 sharepoint 在线下载 XML 文件。

但是,当我使用WebClient.DownloadString(string url)方法时,某些字符未正确解码。

当我使用WebClient.DownloadFile(string url, string file)然后读取文件时,所有字符都是正确的。

xml 本身不包含编码声明。

string wrongXml = webClient.DownloadString(url);
//wrongXml contains Ä™ instead of ?

webClient.DownloadFile(url, @"C:\temp\file1.xml");
string correctXml = File.ReadAllText(@"C:\temp\file1.xml");
//contains ?, like it should.
Run Code Online (Sandbox Code Playgroud)

此外,当在 Internet Explorer 中打开 url 时,它会正确显示。

这是为什么?是因为我的机器上的默认 Windows 编码或 web 客户端在使用 DownloadString 或 DownloadFile 时处理响应的方式不同吗?

Pat*_*man 3

可能它现在使用的编码不是服务返回的编码。

您可以在发出请求之前设置您期望的编码:

webClient.Encoding = Encoding.UTF8;
string previouslyWrongXml = webClient.DownloadString(url);
Run Code Online (Sandbox Code Playgroud)