使用C#将图像从URL保存到本地硬盘

时间:2017-05-27 16:17:57

标签: c#

我正在尝试编写一个控制台应用程序,以便将给定路径中的单个图像存储到新目录中,如article中所述。尽管我的程序没有丢失任何错误,但我想要下载的图像却不会显示在我的文件夹中。我想那是因为我从来没有告诉我的程序我想要保存文件的位置?但是,我还没有发现任何澄清我现在遇到的这个特殊问题的事情。我也提到了thisthis的问题。


using System;
using System.IO;
using System.Net;

namespace GetImages
{
class Program
{
    static void Main(string[] args)
    {
        string dirPath = @"C:\Users\Stefan\Desktop\Images";

        try
        {
            // Create a new directory
            DirectoryInfo imageDirectory = Directory.CreateDirectory(dirPath);
            Console.WriteLine($"Directory '{Path.GetFileName(dirPath)}' was created successfully in {Directory.GetParent(dirPath)}");

            // Image I'm trying to download from the web
            string filePath = @"http://ilarge.lisimg.com/image/12056736/1080full-jessica-clements.jpg";

            using (WebClient _wc = new WebClient())
            {
                _wc.DownloadFileAsync(new Uri(filePath), Path.GetFileName(filePath));
                _wc.Dispose();
            }

            Console.WriteLine("\nFile successfully saved.");
        }

        catch(Exception e)
        {
            while (e != null)
            {
                Console.WriteLine(e.Message);
                e = e.InnerException;
            }
        }            

        if (System.Diagnostics.Debugger.IsAttached)
        {
            Console.WriteLine("Press any key to continue . . .");
            Console.ReadKey(true);
        }
    }
}

}


修改>一段时间后,我发现该文件已保存在"C:\Users\Stefan\Documents\Visual Studio 2017\Projects\GetImages\GetImages\bin\Debug"中。但是,如何将文件直接保存到dirPath,而不将其分别从Debug移至dirPath?我的下一步是扩展此程序以一次保存多个文件。

2 个答案:

答案 0 :(得分:2)

DownloadFileAsync的第二个参数是保存位置,因此将您创建的路径和URL中的文件名组合在一起:

_wc.DownloadFileAsync(new Uri(filePath), Path.Combine(dirPath, Path.GetFileName(filePath)));

答案 1 :(得分:0)

试试这个:

using (WebClient _wc = new WebClient())
            {
                _wc.DownloadFileAsync(new Uri(filePath), Path.Combine(dirPath,Path.GetFileName(filePath)));

            }
相关问题