简体   繁体   中英

C# WebClient.DownloadFile issue with UrlEncoding

I have an url like this https://example.com/4654ds-dsds5-982/file%20%281%29.pdf?token=xxxxxxxx

I use WebClient.DownloadFile to download this file but the URL changed to https://example.com/4654ds-dsds5-982/file%20(1).pdf?token=xxxxxxxx when String is converted to Uri

using (WebClient wc = new WebClient()) {
    wc.DownloadFile(new Uri(myURL), myPATH);
}

My problem is the token to download file is sync with the file name give by the API we use so the URL must be exactly the same (with the same encoded characters)

Any suggestion to download a file from URL without my input URL changed ?

You can try to use the old HttpWebRequest class

var url = " https://example.com/4654ds-dsds5-982/file%20%281%29.pdf?token=xxxxxxxx";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    var destination = "<some local folder>";
    var responseStream = response.GetResponseStream();
    using (var fileStream = File.Create(destination))
    {
        responseStream.CopyTo(fileStream);
    }
}

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