下载完成后打开文件

时间:2012-03-10 14:50:45

标签: c# file-io download

以下代码不起作用,不知何故我无法从'Completed'方法获取int值到我的btn_Start_Click方法:

private void btn_Start_Click(object sender, EventArgs e)
{
    int completedDownload = 0;      

    WebClient webClient = new WebClient();
    webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
    webClient.DownloadFileAsync(new Uri("http://somesite.com/file.jpg"), @"c:\file.jpg");

    if (Completed.completeDownload == 1)
    {
        //open the file code goes here.
    }

    //Rest of the code goes here.
    //and here
    //and here
}

private void Completed(object sender, AsyncCompletedEventArgs e)
{
    completedDownload = 1;
}

2 个答案:

答案 0 :(得分:2)

来自WebClient.DownloadFileAsync函数的评论:

  

使用以下的线程资源异步下载文件   从线程池自动分配。接收通知   当文件可用时,添加一个事件处理程序   DownloadFileCompleted事件。

MSDN Documentation

在文件完成时触发函数似乎是一个更好的选择,它将涉及使用事件处理程序。以下是使用DownloadFileCompleted处理程序的示例:

// Sample call : DownLoadFileInBackground2 ("http://www.contoso.com/logs/January.txt");
public static void DownLoadFileInBackground2 (string address)
{
    WebClient client = new WebClient ();
    Uri uri = new Uri(address);

    // Specify that the DownloadFileCallback method gets called
    // when the download completes.
    client.DownloadFileCompleted += new AsyncCompletedEventHandler (DownloadFileCallback2);
    // Specify a progress notification handler.
    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
    client.DownloadFileAsync (uri, "serverdata.txt");
}

MSDN Documentation

答案 1 :(得分:1)

Completed处理程序异步执行。当您检查该int时,并不保证hanlder已设置该值。如果要在下载完成时执行某些操作,请在“已完成”方法中执行此操作。