Cameron Tinker
Cameron Tinker

Reputation: 9789

Trying to download a file with WebClient that contains a ':' in the URL

I'm trying to download a file with a colon ':' in the URL and I get an exception with that character in the URL string. For example: http://www.somesite.com/url:1/ 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:

WebClient wc = new WebClient();
wc.DownloadFile("http://www.somesite.com/url:1/", somePath);

Upvotes: 2

Views: 2848

Answers (5)

Marc Gravell
Marc Gravell

Reputation: 1062745

WebClient has no complaint about this:

using(var client = new WebClient())
{
    try
    {
        client.DownloadFile(
            "http://stackoverflow.com/users/541404/fake:1",
            @"j:\MyPath\541404.html");
    }
    catch (Exception ex)
    {
        while (ex != null)
        {
            Console.WriteLine(ex.Message);
            ex = ex.InnerException;
        }
    }
}

works fine. So; I think you need to look again at the Exception (and any InnerException), to see what the problem actually is.

Upvotes: 1

Nikola Radosavljević
Nikola Radosavljević

Reputation: 6911

Many special characters can't be contained in path part of the URL. You will have to encode that part and concatenate it with server address. You can do this using HttpUtility.UrlEncode

string url = "http://www.somesite.com/" + HttpUtility.UrlEncode("url:1/");

Upvotes: 2

Evan Dark
Evan Dark

Reputation: 1341

I'm not an expert on this, but all browsers subsititute illegal characters with "%" + ASCII code (hexa), so maybe you can try "%3A" instead ":". Like: "http://www.somesite.com/url:1/"

Upvotes: 0

SliverNinja - MSFT
SliverNinja - MSFT

Reputation: 31641

You need to encode the URI using HttpUtility.UrlEncode. See this example. If it is static than just use the fixed character translation (%3A).

Upvotes: 1

Mathieu
Mathieu

Reputation: 3083

You could try to URL encode the colon (%3A).

I always use this site to encode or decode URL's.

Your example would be like this then:

WebClient wc = new WebClient();
wc.DownloadFile("http://www.somesite.com/url%3A1/", somePath);

Upvotes: 4

Related Questions