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.
![Image 1](/KB/cs/679518/Capture1-r-700.JPG)
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");
}
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.