Ali Vojdanian
Ali Vojdanian

Reputation: 2111

download a file

I use these following codes to download a file from a specific url in C# windows application.

private void button1_Click(object sender, EventArgs e)
{
    string url = @"DOWNLOADLINK";
    WebClient web = new WebClient();
    web.DownloadFileCompleted += new AsyncCompletedEventHandler(web_DownloadFileCompleted);
    web.DownloadFile(new Uri(url), @"F:\a");
}

void web_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    MessageBox.Show("The file has been downloaded");
}

But it has an error for this line : web.DownloadFile(new Uri(url), @"F:\a");

It says :

An exception occurred during a WebClient request.

Upvotes: 0

Views: 1039

Answers (1)

tomfanning
tomfanning

Reputation: 9670

No need for the event handler if you use DownloadFile rather than DownloadFileAsync.

Update: From chat it turned out that the OP wanted the filename on the filesystem to reflect the filename specified at the end of the URL. This is the solution:

private void button1_Click(object sender, EventArgs e)
{
    Uri uri = new Uri("http://www.yourserver/path/to/yourfile.zip");
    string filename = Path.GetFileName(uri.LocalPath);

    WebClient web = new WebClient();
    web.DownloadFile(new Uri(url), Path.Combine(@"f:\", filename));
}

Upvotes: 2

Related Questions