Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Download any file from website through console application in C#

0.00/5 (No votes)
7 Nov 2013 1  
Download any file from website through console application in C#.

Hi friends, in today's example Ii would show you how to download any file from any website using C# through a console application. For this we consider that we want to download some Excel file from http://www.testblog.com. As we see in the below snap, we have four links and we want to download those files through our console application.

 

For this first you have to download HtmlAgilityPack

private static void DownloadXlsFiles(string filePath)  
{  
   WebClient wc = new WebClient();  
   var sourceCode = wc.DownloadString("www.testblog.com");  
   HtmlDocument doc = new HtmlDocument();  
   doc.LoadHtml(sourceCode);  
   var node = doc.DocumentNode;  
   var nodes = node.SelectNodes("//a");  
   List<string> links = new List<string>();  
   foreach (var item in nodes)  
   {  
     var link = item.Attributes["href"].Value;  
     links.Add(link.Contains("http") ? link : "www.testblog.com" + link);  
   }  
   List<string> xlsLinks = new List<string>();  
   foreach (string s in links)  
   {  
     if (s.LastIndexOf(".xls") != -1)  
     {  
       xlsLinks.Add(s.ToString());  
     }  
   }  
   foreach (string file in xlsLinks)  
   {  
     string[] fileName = file.Split('/');  
     if (fileName.Length > 0)  
     {  
       WebClient webClient = new WebClient();  
       webClient.DownloadFile(file, filePath + fileName[fileName.Length - 1].ToString());  
       Console.WriteLine(fileName[fileName.Length - 1].ToString() + " download successfully");  
     }  
   }  
   Console.WriteLine("All files download successfully");  
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here