【问题标题】:C# WebClient.DownloadFile issue with UrlEncodingUrlEncoding 的 C# WebClient.DownloadFile 问题
【发布时间】:2018-10-11 15:05:14
【问题描述】:

我有一个这样的网址https://example.com/4654ds-dsds5-982/file%20%281%29.pdf?token=xxxxxxxx

我使用 WebClient.DownloadFile 来下载这个文件,但是当 String 转换为 Uri 时 URL 更改为 https://example.com/4654ds-dsds5-982/file%20(1).pdf?token=xxxxxxxx

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

我的问题是下载文件的令牌与我们使用的 API 提供的文件名同步,因此 URL 必须完全相同(具有相同的编码字符)

在不更改我的输入 URL 的情况下从 URL 下载文件有什么建议吗?

【问题讨论】:

    标签: c# webclient


    【解决方案1】:

    你可以尝试使用旧的 HttpWebRequest 类

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

    【讨论】:

    • 同样的问题。如果您打印 request.RequestUri.AbsoluteUri 的结果,您可以看到 Uri 已更改。可以看到 HttpWebRequest.Create(string uri) 方法将字符串转换为 Uri Microsoft source
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    相关资源
    最近更新 更多