Title: Download files from the web in C#
The WebClient class makes it pretty easy to download files from the web and save them in local files in C#. The following code shows how the program responds when you click the Download button.
private void btnDownload_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
Application.DoEvents();
try
{
// Make a WebClient.
WebClient web_client = new WebClient();
// Download the file.
web_client.DownloadFile(txtRemoteFile.Text,
txtLocalFile.Text);
MessageBox.Show("Done");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Download Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
this.Cursor = Cursors.Default;
}
The code simply creates a WebClient object and invokes its DownloadFile method passing it the remote file's URL and the destination file's name. That's all you need to do to download files from the web, at least in the simple case. (If you need to work through firewalls or if the filers are not publicly available, things get more complicated.)
Download the example to experiment with it and to see additional details.
|