2. Main code:
Private async void Button_Click (object sender, RoutedEventArgs e) {var htmlcontent = await filedownload Er. Instance.getasync (Weburl.text); Htmlagilitypack.htmldocument doc = new htmlagilitypack.htmldocument (); Doc. Loadhtml (htmlcontent); Label1. Content = ""; var nodecollection= doc. Documentnode.selectnodes ("//img"); if (nodecollection!=null) {string imgdirectory = System.IO.Path.Combine (environment.currentdirec Tory, "IMGs"); if (! Directory.Exists (imgdirectory)) {directory.createdirectory (imgdirectory); } progressbar.maximum = Nodecollection.count; Progressbar.value = 0; int errorcount = 0; foreach (var item in nodecollection) {progressbar.value + = 1; try {var imgsrc=item.Getattributevalue ("src", null); myimg img = new myimg (IMGSRC); if (!string. IsNullOrEmpty (IMG. FileName) {await FileDownLoader.Instance.DownLoadImg (IMG, imgdirectory) ; }} catch (Exception ex) {Errorcount + = 1; } Label1. Content = "+progressbar.value+" photos, total "+ progressbar.maximum+" pictures, "+errorcount+" error "; } progressbar.value = Progressbar.maximum; }
Public class Filedownloader { HttpClient HttpClient = new HttpClient (); public static Filedownloader Instance = new Filedownloader (); Public async Task downloadimg (myimg img,string imgdirectory) { var imgdata = await Httpclient.getbytearrayasync (IMG. IMGSRC); String newfilename = System.IO.Path.Combine (Imgdirectory, IMG. FileName); using (var stream = File.Open (NewFileName, FileMode.Create)) { await stream. WriteAsync (imgdata, 0, imgdata.length); }; } Public Async task<string> getasync (string url) { var response= await httpclient.getasync (URL); return await response. Content.readasstringasync (); } }
public class myimg {public myimg (string imgsrc) { if (imgsrc! = null) { var startIndex = imgsrc . LastIndexOf (@ "/"); var startIndex1 = Imgsrc.lastindexof ("."); FileName = imgsrc.substring (StartIndex + 1, Startindex1-startindex + 3); IMGSRC = imgsrc; } } public string FileName {get; set;} public string Imgsrc {get; set;} }
Download pictures in bulk