2017-05-27 89 views
0

我试图编写控制台应用程序,以便将来自给定路径的单个图像存储到此目录中,如article中所建议的那样。尽管我的程序没有抛出任何错误,但我想要下载的图像不会显示在我的文件夹中。我想那是因为我从来没有告诉我的程序我想要保存文件的位置?但是,我还没有发现任何澄清我现在有这个特殊问题的任何事情。我已经提到了thisthis问题。使用C#将图像从URL保存到本地硬盘驱动器


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?我的下一步就是扩展这个程序来一次保存多个文件。

+1

首先你不需要的'_wc.Dispose();'当你使用'WebClient _wc = new WebClient())'时,它会自动执行 –

回答

2

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

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

试试这个:

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

      }