English 中文(简体)
WebClient.DownloadFileAsync正在服务器上下载文件
原标题:WebClient.DownloadFileAsync downloading the file on server

我正在将一个文件从远程位置下载到本地计算机。我使用的路径保存在web.config中,格式如下:

<add key="FileFolder" value="Files/"/>
<add key="LocalFileFolder" value="D:REAL" />

我用来下载的代码是:

  CreateDirectoryIfDoesNotExist();
  WebClient webClient = new WebClient();
  webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
  webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
  webClient.DownloadFileAsync(new Uri(context.Server.MapPath(ConfigurationManager.AppSettings["FileFolder"].ToString() + myfilename)), ConfigurationManager.AppSettings["LocalFileFolder"].ToString() + myfilename);

当我在服务器上部署它时;在运行我的程序时,我收到一条消息,说下载已经成功完成。但问题是该文件是在服务器机器上的文件文件夹(LocalFileFolder)中下载的。我想把它下载到本地机器上。我做错了什么?

问题回答

您的错误之处在于您正在服务器上运行此代码。如果这是一个web应用程序(我想这是因为您使用的是HttpContext),您需要将文件流式传输到响应,而不是使用WebClient。然后,用户在浏览器中获得一个下载对话框,并选择将文件保存到他想要的任何位置(不能覆盖此选项)。

因此:

context.Response.ContentType = "text/plain";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=foo.txt");
context.Response.TransmitFile(@"d:pathonserversomefile.txt");

或者,您可以编写一个桌面应用程序(WPF、WinForms),在客户端计算机上运行,并使用WebClient从远程服务器位置下载文件。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Transaction handling with TransactionScope

I am implementing Transaction using TransactionScope with the help this MSDN article http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx I just want to confirm that is ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签