使用webclient从已部署的网站下载图像

时间:2013-09-06 03:18:50

标签: c# asp.net wpf download webclient

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

  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应用程序文件夹中?

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

1 个答案:

答案 0 :(得分:1)

首先,WebClient类已经有了一个方法。使用类似client.DownloadFile(remoteUrl, localFilePath)的内容。

请看这个链接:

WebClient.DownloadFile Method (String, String)

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

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

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

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