如何从重定向的URL下载文件?

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

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的解决方案。

通过具有重定向的代码下载文件?

 // 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的参数。 但是如何将文件检索到我的目录? 是的,我是noob …先谢谢你的帮助。

我想简单的选择就是这个(在你到达那里之后……以及你提供的URL代替http://www.contoso.com ):

 using (var responseStream = myHttpWebResponse.GetResponseStream()) { using (var fileStream = new FileStream(Path.Combine("folder_here", "filename_here"), FileMode.Create)) { responseStream.CopyTo(fileStream); } } 

编辑:

事实上,这是行不通的。 它不是下载文件的HTTP重定向。 看看那个页面的来源……你会看到这个:

  

它主要使用浏览器重定向。 不幸的是,你要做的事情是行不通的。

我也从基于WebClient的方法切换到HttpWebRequest因为自动重定向似乎不适用于WebClient 。 我使用类似的代码到你的,但永远不能让它工作,它从来没有重定向到实际的文件。 看着提琴手我可以看到我实际上没有得到最后的重定向。

然后我在这个问题中遇到了一些WebClient自定义版本的代码:

 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 ,默认情况下它应该根据文档打开, 该文档指出:

在WebClient实例中,AllowAutoRedirect设置为true。

但是当我使用它时似乎并非如此。

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