开发者

WebClient.DownloadFileAsync downloading the file on server

开发者 https://www.devze.com 2023-01-22 07:37 出处:网络
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 i开发者_如何学编程n following format:

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 i开发者_如何学编程n 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消