C#實現(xiàn)批量下載圖片到本地示例代碼
一、概述
批量下載圖片是我們在日常開發(fā)中經(jīng)常會遇到的一個需求,這不,最近工作中就需要批量下載圖片到本地,先是通過Excel拼接生成了所有鏈接地址,然后想到的是通過下載軟件來批量下載。可是一想到又要花時間去查找、安裝、研究軟件,不如自己寫個來的快。
以下是使用C#開發(fā)的控制臺程序代碼,通過循環(huán)讀取文本文件中每一行地址字符串,執(zhí)行下載并保存到本地文件夾中。
下面話不多說了,來一起看看詳細的介紹吧
二、C#實例代碼
//using System; //using System.Net; //using System.Text; //using System.IO; //-------------------------------------------- static void Main(string[] args) { //StreamReader讀取 int count = 0; using (Stream readerStream = new FileStream(@"d:\list.txt", FileMode.Open)) using (StreamReader reader = new StreamReader(readerStream, Encoding.UTF8)) using (WebClient client = new WebClient()) { string line; while ((line = reader.ReadLine()) != null) { count++; Console.WriteLine(line + " " + count); Uri uri = new Uri(line); if (uri!=null) { string filename = Path.GetFileName(uri.LocalPath); client.DownloadFile(uri, @"c:\pictures\"+filename); Console.WriteLine("文件:"+filename+" 下載成功!" + " 計數(shù):"+ count); } else { Console.WriteLine("路徑:" + line + " 不是下載地址!失敗序號:"+count ); } } } Console.WriteLine("下載完成!"); Console.ReadKey(); }
三、參考文章
How to download image from url
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。