Download a file from the web and save it with an arbitrary local file name in C#

This is actually pretty easy using a WebClient object.

First, add a "using System.Net" statement to the top of the file.

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 there is to it!

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.