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



我尝试编写控制台应用程序,以便将给定路径中的单个图像存储到本文建议的新目录中。尽管我的程序没有抛出任何错误,但我想下载的图像不会显示在我的文件夹中。我想那是因为我从未告诉我的程序我希望将文件保存在哪里?但是,我还没有找到任何可以澄清我现在遇到的这个特定问题的东西。我也已经提到了这个问题和这个问题。


using System;
using System.IO;
using System.Net;
namespace GetImages
{
class Program
{
    static void Main(string[] args)
    {
        string dirPath = @"C:UsersStefanDesktopImages";
        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:UsersStefanDocumentsVisual Studio 2017ProjectsGetImagesGetImagesbinDebug"中。但是,如何在不将它们分别从Debug移动到dirPath的情况下将文件直接保存到dirPath?我的下一步是扩展此程序以一次保存多个文件。

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

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

试试这个:

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

最新更新