如何从重定向的url下载文件? [英] How to download file from url that redirects?

查看:415
本文介绍了如何从重定向的url下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i'm trying to download a file from a link that doesn't contain the file, but instead it redirects to another (temporary) link that contains the actual file. The objective is to get an updated copy of the program without the need to open a browser. The link is:

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

我试图使用WebClient,但不会工作:

I've tried to use WebClient, but it won't work:

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

在搜索和尝试许多事情后,我发现这个解决方案涉及使用< a href =http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.allowautoredirect.aspx =nofollow noreferrer> HttpWebRequest.AllowAutoRedirect 。

After searching and trying many things i've found this solution that involves using 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 ...提前感谢你的帮助。

It seems that's exactly what i'm looking for, but i simply don't know how to use it :/ I guess the link is a parameter of WebRequest.Create. But how can i retrieve the file to my directory? yes, i´m a noob... Thanks in advance for your help.

推荐答案

我猜这个简单的选择就是这样在你所在的地方,你提供的网址代替 http://www.contoso.com ):

I guess the easy option is simply this (after what you've got there.. and the URL you provided in place of 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重定向。看看该页面的来源..你会看到这样的:

In fact, this won't work. It isn't a HTTP redirect that downloads the file. Look at the source of that page.. you'll see this:

<meta http-equiv="refresh" content="3; url=http://download.bleepingcomputer.com/dl/1f92ae2ecf0ba549294300363e9e92a8/52ee41aa/windows/security/security-utilities/m/minitoolbox/MiniToolBox.exe">

它基本上使用浏览器重定向。不幸的是你要做的不行。

It basically uses the browser to redirect. Unfortunately what you're trying to do won't work.

这篇关于如何从重定向的url下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆