views:

29

answers:

1

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  A: 

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.

Darin Dimitrov
but i have to deploy my code on some machine. what else should i do then?
ria
In the case of web application you deploy your code on the server. In case you decide to write a windows application you deploy your code on the client.
Darin Dimitrov
thanks ... i m trying it now ... but will it handle huge files ? i have a maximum file size limit of 18 MB, i hope this code will not break with this much amount of data?
ria
There should be no problems sending an 18MB file from an ASP.NET application to the response stream. There's a default limit for [uploading files](http://weblogs.asp.net/jgalloway/archive/2008/01/08/large-file-uploads-in-asp-net.aspx) which could be adjusted.
Darin Dimitrov