Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebClient.DownloadString uses wrong encoding

I'm downloading XML files from sharepoint online using webclient.

However, when I use WebClient.DownloadString(string url) method, some characters are not correctly decoded.

When I use WebClient.DownloadFile(string url, string file) and then I read the file all characters are correct.

The xml itself does not contain encoding declaration.

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.

Also, when open the url in Internet Explorer, it is shown correctly.

Why is that? Is it because of the default windows encoding on my machine or webclient handles responses differently when using DownloadString, resp DownloadFile?

like image 938
Liero Avatar asked Oct 18 '22 00:10

Liero


1 Answers

Probably the encoding it is using now is not the one the service returns.

You can set the encoding you expect before you make the request:

webClient.Encoding = Encoding.UTF8;
string previouslyWrongXml = webClient.DownloadString(url);
like image 73
Patrick Hofman Avatar answered Oct 21 '22 00:10

Patrick Hofman