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