How do I programmatically download a file from a specified URL?

Hi Experts

I am looking for a snippet of code that will allow me to programmatically download a zip or xml file from a specified URL on the web. The code will have to work from a WPF program, so it is windows based. The URL and file will be on a domain that I administrate, so I will have full read/write access to the file. I will also want to save the file to a folder on the local C-drive.
Who is Participating?
Jaime OlivaresConnect With a Mentor Software ArchitectCommented:
use the System.Net.WebClient class, like:

System.Net.WebClient Client = new System.Net.WebClient ();
Client.DownloadFile("", @"c:\somefolder\");
Using a stream is the easiest and safest way to read a file on a client machine.  Hope this code helps:

Using Microsoft.Win32;
Using System.IO;
// Put this section of code in your function
/************ BEGIN ******************************************/
OpenFileDialog openDialog = new OpenFileDialog();
// Setup your file filters here
openDialog.Filter = "Text Files (*.txt)|*.txt|All files (*.*)|*.*";
// Variable that stores your file data
string fileData;
if (openDialog.ShowDialog() == true)
	using (Stream fileStream = openDialog.OpenFile())
		int numBytesToRead = (int)fileStream.Length;
		byte[] bytes = new byte[numBytesToRead];
		int numBytesRead = 0;
		while (numBytesToRead > 0)
			int n = fileStream.Read(bytes, numBytesRead, numBytesToRead);
			if (n == 0)
			numBytesRead += n;
			numBytesToRead -= n;
                  // This variable has your file data.
		fileData = Encoding.ASCII.GetString(bytes);
/************ END ******************************************/

Open in new window

esesjay4Commented: code requires the user to actually select the file.  So this might not work for you...sorry.
Fritz41Author Commented:
Thanks, this seems like exactly what I was looking for.
All Courses

From novice to tech pro — start learning today.