【问题标题】:C# Download file from URLC# 从 URL 下载文件
【发布时间】:2015-09-22 13:34:14
【问题描述】:

谁能告诉我如何从该 URL 下载我的 C# 程序中的文件: http://www.cryptopro.ru/products/cades/plugin/get_2_0

我尝试使用 WebClient.DownloadFile,但我得到的只是 html 页面而不是文件。

【问题讨论】:

  • 嗯,你的 url 指向一个 html 文件,这就是你得到的。您要下载哪个文件?
  • 如果您尝试在任何浏览器中打开该 URL,下载就会开始。

标签: c# file download


【解决方案1】:

如果没有合法的 U/A 字符串,则在 Fiddler 中查找请求失败,因此:

WebClient wb = new WebClient();
wb.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.33 Safari/537.36");
wb.DownloadFile("http://www.cryptopro.ru/products/cades/plugin/get_2_0/cadeplugin.exe", "c:\\xxx\\xxx.exe");

【讨论】:

  • 我在上面添加了标题,但它对我不起作用。我正在尝试下载加密文本和 exe 文件。
【解决方案2】:

我相信这会成功。

WebClient wb = new WebClient();
wb.DownloadFile("http://www.cryptopro.ru/products/cades/plugin/get_2_0/cadeplugin.exe","file.exe");

【讨论】:

    【解决方案3】:

    如果您需要知道下载状态或使用凭据来发出请求,我会建议这个解决方案:

    WebClient client = new WebClient();
    Uri ur = new Uri("http://remoteserver.do/images/img.jpg");
    client.Credentials = new NetworkCredential("username", "password");
    client.DownloadProgressChanged += WebClientDownloadProgressChanged;
    client.DownloadDataCompleted += WebClientDownloadCompleted;
    client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");
    

    而她是回调的实现:

    void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);
    }
    
    void WebClientDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
    {
        Console.WriteLine("Download finished!");
    }
    

    【讨论】:

    • 应该是 DownloadFileCompleted 而不是 DownloadDataCompleted。
    【解决方案4】:

    试试WebClient.DownloadData

    您会以byte[] 的形式收到回复,然后您可以随心所欲。

    【讨论】:

      【解决方案5】:

      有时服务器不允许您下载带有脚本/代码的文件。为了解决这个问题,您需要设置用户代理标头以欺骗服务器,该请求来自浏览器。使用以下代码,它可以工作。测试正常

       var webClient=new WebClient();
       webClient.Headers["User-Agent"] =
                      "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36";
       webClient.DownloadFile("the url","path to downloaded file");
      

      这将按您的预期工作,您可以下载文件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-23
        • 2010-09-23
        相关资源
        最近更新 更多