简体   繁体   中英

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);

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);

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/");

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

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.

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/"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM