c# - 如何从重定向的网址下载文件?

标签 c# redirect download httpwebrequest

我正在尝试从不包含文件的链接下载文件,而是重定向到包含实际文件的另一个(临时)链接。目的是在无需打开浏览器的情况下获取程序的更新副本。链接是:

http://www.bleepingcomputer.com/download/minitoolbox/dl/65/

我试过使用 WebClient,但它不起作用:

private void Button1_Click(object sender, EventArgs e)
{
      WebClient webClient = new WebClient();
      webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
      webClient.DownloadFileAsync(new Uri("http://www.bleepingcomputer.com/download/minitoolbox/dl/65/"), @"C:\Downloads\MiniToolBox.exe");
}

在搜索和尝试很多事情之后,我发现了这个涉及使用 HttpWebRequest.AllowAutoRedirect 的解决方案.

Download file through code that has a redirect?

// Create a new HttpWebRequest Object to the mentioned URL.
HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://www.contoso.com");    
myHttpWebRequest.MaximumAutomaticRedirections=1;
myHttpWebRequest.AllowAutoRedirect=true;
HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();

这似乎正是我要找的东西,但我只是不知道如何使用它:/ 我猜链接是 WebRequest.Create 的一个参数。但是我怎样才能将文件检索到我的目录中呢?是的,我是菜鸟...在此先感谢您的帮助。

最佳答案

我也从基于 WebClient 的方法切换到 HttpWebRequest,因为自动重定向似乎不适用于 WebClient。我使用的代码与您的类似,但永远无法正常工作,它从未重定向到实际文件。查看 Fiddler,我发现我实际上并没有获得最终的重定向。

然后我发现了一些自定义版本的 WebClient 的代码 in this question :

class CustomWebclient: WebClient
{
  [System.Security.SecuritySafeCritical]
  public CustomWebclient(): base()
  {
  }

  public CookieContainer cookieContainer = new CookieContainer();

  protected override WebRequest GetWebRequest(Uri myAddress)
  {
    WebRequest request = base.GetWebRequest(myAddress);
    if (request is HttpWebRequest)
    {
      (request as HttpWebRequest).CookieContainer =   cookieContainer;
      (request as HttpWebRequest).AllowAutoRedirect = true;
    }
    return request;
  }
}

该代码中的关键部分是AllowAutoRedirect = true,它应该默认打开according to the documentation ,其中指出:

AllowAutoRedirect is set to true in WebClient instances.

但是我用的时候好像不是这样。

我还需要 CookieContainer 部分来处理我们尝试访问的 SharePoint 外部 URL。

关于c# - 如何从重定向的网址下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21510762/

相关文章:

python - 从 Flask 返回重定向到 S3 不会下载文件

php - 在 PHP 中传递错误消息

java - 让 Selenium 等待文件下载完成

java - Struts 2 在下载时自动打开 .doc 或 .docx

java - 通过文件 URL 将文件发送到客户端,无需在服务器上下载

c# - 使用空日期时通用化命令参数创建

c# - 如何在紧凑框架中从字节数组加载程序集

c# - TlbExp.exe 错误 :This assembly is built by a runtime newer

c# - 这是一个错误吗?具有私有(private)访问修饰符构造函数的 Activator.CreateInstance?

php - 如何在没有尾部斜杠的情况下访问目录的index.php并且不获得301重定向