Search code examples
c#webclient

c# Trying to download a file with WebClient that contains a special character in filename


I'm trying to download a file with a special character 'Ç' for example in the filename, I get an exception with that character in the URL string.

System.Net.WebException
HResult=0x80131509
Message=The remote server returned an error: (404) Not Found.
Source=System.Net.Requests

For example: http://www.somesite.com/abcdç.pdf would create an exception in the WebClient. What is another way to download files using URI or how can I fix this exception?

Here's some sample code:

client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
client.Encoding = System.Text.Encoding.UTF8;
byte[] archiveData = wc.DownloadData("http://www.somesite.com/abcdç.pdf");

Solution

  • You could try using Uri encoding for the special character, eg.

    www.somesite.com/abcd%C3%A7.pdf
    

    You can get a safe Uri like this

    Uri u = new Uri("http://www.somesite.com/abcdç.pdf");
    byte[] archiveData = wc.DownloadData(u.AbsoluteUri);
    

    u.AbsoluteUri will give you an encoded URI.