我下载从远程位置的文件,以我的本地机器。我使用的路径保存在web.config中并在格式如下:
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\" />在code我使用的是下载:
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);当我在服务器上部署;并运行我的程序,我得到一个消息,说下载已成功完成。但问题是,该文件在filefolder(LocalFileFolder)在服务器机器上下载。我希望它可以在本地计算机上下载。它是什么,我做错了?
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?
推荐答案你在做什么错的是正在运行在服务器上的这个code。如果这是一个Web应用程序(我猜那是因为你正在使用的HttpContext),你需要以流式传输文件的响应,而不是使用Web客户端。然后,用户在得到他的浏览器下载对话框,选择文件保存的地方,他希望(你不能覆盖此)。
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).
所以:
context.Response.ContentType = "text/plain"; context.Response.AppendHeader("Content-Disposition", "attachment; filename=foo.txt"); context.Response.TransmitFile(@"d:\pathonserver\somefile.txt");或者,你可以写你在客户机上运行,它使用Web客户端从远程服务器位置下载文件的桌面应用程序(WPF,WinForms的)。
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.
更多推荐
WebClient.DownloadFileAsync下载服务器上的文件
发布评论