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)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!
{
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;
}


Comments