【问题标题】:Using webclient to download images from deployed website使用 webclient 从已部署的网站下载图像
【发布时间】:2013-09-06 03:18:50
【问题描述】:

我在 localhost/xxx/xxx.aspx 上运行的 IIS 上部署了一个网站。在我的 WPF 端,我使用 webclient 从 localhost 服务器下载一个文本文件并将其保存在我的 wpf 应用程序文件夹中 我就是这样做的:

  protected void DownloadData(string strFileUrlToDownload)
    {
        WebClient client = new WebClient();
        byte[] myDataBuffer = client.DownloadData(strFileUrlToDownload);         

        MemoryStream storeStream = new MemoryStream();

        storeStream.SetLength(myDataBuffer.Length);
        storeStream.Write(myDataBuffer, 0 , (int)storeStream.Length);

        storeStream.Flush();

        string currentpath = System.IO.Directory.GetCurrentDirectory() + @"\Folder";

        using (FileStream file = new FileStream(currentpath, FileMode.Create, System.IO.FileAccess.ReadWrite))
        {
            byte[] bytes = new byte[storeStream.Length];
            storeStream.Read(bytes, 0, (int)storeStream.Length);
            file.Write(myDataBuffer, 0, (int)storeStream.Length);
            storeStream.Close();
        }

        //The below Getstring method to get data in raw format and manipulate it as per requirement
        string download = Encoding.ASCII.GetString(myDataBuffer);


    }

这是通过编写 btyes 并保存它们。但是如何下载多个图像文件并将其保存在我的 WPF 应用程序文件夹中?我有一个像 localhost/websitename/folder/designs/ 这样的 URL,在这个 URL 下,有很多图片,我如何下载所有图片?并将其保存在 WPF 应用程序文件夹中?

基本上我想下载文件夹的内容,其中的内容实际上是图像。

【问题讨论】:

  • 为什么在FileStream 上使用using,而不是MemoryStreamWebClient

标签: c# asp.net wpf download webclient


【解决方案1】:

首先,WebClient 类已经为此提供了一个方法。使用 client.DownloadFile(remoteUrl, localFilePath) 之类的东西。

查看此链接:

WebClient.DownloadFile Method (String, String)

其次,您需要以某种方式为要在服务器上下载的文件编制索引。您不能只通过 HTTP 获取目录列表,然后循环遍历它。需要将 Web 服务器配置为启用目录列表,或者您将需要一个页面来生成目录列表。然后,您需要使用WebClient.DownloadString 将该页面的结果作为字符串下载并解析。一个简单的解决方案是一个 aspx 页面,它输出您要下载的目录中的文件的明文列表。

最后,在您发布的代码中,您将下载的每个文件都保存为一个名为“文件夹”的文件。您需要为要下载的每个文件生成一个唯一的文件名。当您循环浏览要下载的文件时,请使用以下内容:

string localFilePath = Path.Combine("MyDownloadFolder", imageName);

其中imageName 是该文件的唯一文件名(带有文件扩展名)。

【讨论】:

  • 我不明白你的意思是下载页面结果并解析它,你的意思是我所有图片所在的页面?但是没有页面,它只有一个文件夹。
  • 我可以下载文件,但它是 1 by 1 的,我想把它全部下载并保存到一个文件夹中
  • 您不能简单地从网络服务器“下载所有内容”。这不是 Web 服务器支持的。除非您事先知道该文件夹中的所有文件,否则您需要从 Web 服务器请求文件列表,然后使用该列表单独下载每个文件。你为什么还要这样做?我有 99% 的把握,您尝试做的事情不是您需要做的事情,而且您只是一个新的程序员,让自己的生活变得更加困难。
  • 但它在我的目录中..不在我的任何页面中....我如何请求它们? Downloadstring 只下载页面?
  • 没错。简单地说,通过 HTTP 你只能下载页面/文件。你需要在服务器上创建你自己的页面,列出你想要的目录的内容。然后,您的客户端将下载该页面并使用该列表单独下载每个文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-08
  • 2018-10-22
  • 2020-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多