Have you ever had the need to download a bunch of files and didn't want to type them in manually into your browser?
Have you ever been to a webpage that lists files in non-hyperlinked lists?
Do you want to learn how to download files using ASP.NET?
If you answered yes to any of the above questions, then you have justified my time coding this ASP.NET file downloading console application.
So let's get started! Let's get an overview of the .NET framework namespaces I'll be using.
System.Net Namespace
So the system.net namespace provides you with a API to many of the networking related protocols used on networks etc. You will find classes Dns, IPAddress, HttpWebRequest, WebProxy and the one we will be using today WebClient.
So the WebClient Class enables you to send and receive data from a URI (Universal Resource Identifiers - see definition). The class contains many properties such as BaseAddress, Headers, Querystring and ResponseHeaders. As for the public methods, you'll find DownloadData, Downloadfile (that I use for this application), OpenRead / OpenWrite, UploadData, UploadFile etc.
So as I noted earlier, I will be using the DownloadFile method, note that the DownloadData method is very similar except that it downloads the data into a byte array.
How the Console Application Downloads Files
My console application (which you can download the c# source code for) is very simple. Let's take a look at the main method that performs the file reading and the actual downloading and saving of the files to a directory.
// get files to download
//
ArrayList rgFiles = Downloader.LoadFiles(Globals.PathToData, "files.txt");
// download
//
Downloader.DownloadAndSave(rgFiles, "../../Data/");
Console.WriteLine("..end " + DateTime.Now);
Console.ReadLine();
We first grab all the files we want to download and load them into an ArrayList.
ArrayList rgFiles = Downloader.LoadFiles(Globals.PathToData, "files.txt");
The file is loaded by using a StreamReader. I simply run through the file line by line (using the Peak method) and store the URI in the file to my ArrayList. I ensure the file is not empty.
StreamReader sr = new StreamReader(strPath);
ArrayList rgFiles = new ArrayList();
while(sr.Peek() >= 0)
{
string line = sr.ReadLine();
if(line.Length > 0)
{
rgFiles.Add(line);
}
}