0

これらの次のコードを使用して、C# Windows アプリケーションで特定の URL からファイルをダウンロードします。

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");
}

しかし、この行にはエラーがあります:web.DownloadFile(new Uri(url), @"F:\a");

それは言います:

WebClient リクエスト中に例外が発生しました。

4

1 に答える 1

2

DownloadFileではなくを使用する場合は、イベントハンドラーは必要ありませんDownloadFileAsync

更新:チャットから、OPはファイルシステム上のファイル名がURLの最後に指定されたファイル名を反映することを望んでいることが判明しました。これが解決策です:

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));
}
于 2012-09-27T21:15:43.993 に答える