【问题标题】:WebClient.DownloadFileAsync downloading the file on serverWebClient.DownloadFileAsync 在服务器上下载文件
【发布时间】:2010-10-25 08:08:09
【问题描述】:

我正在将文件从远程位置下载到本地计算机。我使用的路径保存在 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)中。我希望将其下载到本地计算机上。我到底做错了什么?

【问题讨论】:

    标签: asp.net asynchronous webclient


    【解决方案1】:

    您做错的是您在服务器上运行此代码。如果这是一个 Web 应用程序(我猜这是因为您使用的是 HttpContext),您需要将文件流式传输到响应而不是使用 WebClient。然后用户在他的浏览器中看到一个下载对话框,并选择将文件保存在他想要的任何地方(你不能覆盖它)。

    所以:

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

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

    【讨论】:

    • 但我必须在某些机器上部署我的代码。那我还应该怎么做呢?
    • 对于 Web 应用程序,您将代码部署在服务器上。如果您决定编写 Windows 应用程序,您可以在客户端上部署代码。
    • 谢谢...我现在正在尝试...但它会处理大文件吗?我的最大文件大小限制为 18 MB,我希望这段代码不会因为这么多数据而中断?
    • 从 ASP.NET 应用程序向响应流发送 18MB 文件应该没有问题。 uploading files 有一个默认限制,可以调整。
    猜你喜欢
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 2017-04-22
    相关资源
    最近更新 更多