WebClient.DownloadFileAsync downloading the file on server

好久不见. 提交于 2019-12-11 07:28:59

问题


I am downloading a file from a remote location to my local machine. The paths I am using are saved in web.config and are in following format:

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

the code I am using to download is:

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

When i deploy it on the server; and run my program, i get a message saying that download has completed successfully. But the problem is that the file is downloaded on the server machine in the filefolder (LocalFileFolder). I want it to be downloaded on the local machine. What is it that I am doing wrong?


回答1:


What you are doing wrong is that you are running this code on the server. If this is a web application (I guess it is because you are using HttpContext) you need to stream the file to the response instead of using WebClient. Then the user gets a download dialog in his browser and chooses to save the file wherever he wants (you cannot override this).

So:

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

Or you could write a desktop application (WPF, WinForms) which you run on the client machine and which uses WebClient to download a file from a remote server location.



来源:https://stackoverflow.com/questions/4012791/webclient-downloadfileasync-downloading-the-file-on-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!