2017-05-27 93 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))); 

      }