DownloadFileCompleted Event不会显示简单的MessageBox

时间:2015-06-28 14:38:13

标签: c# webclient

我正在尝试实现WebClient.DownloadFileCompleted事件,主要是在下载被取消时删除该文件。

DownloadFileCompleted事件:

private void _web_client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
        if (e.Cancelled)
        {
            //Delete the file in here
            MessageBox.Show("Download cancelled!"); // Doesn't work
            File.WriteAllText("output.txt", "Test string"); //Works
            throw new Exception("Some Exception"); //Program doesn't crash
        }
        else
        {
            MessageBox.Show("Download succeeded!"); // Works
        }
}

FormClosing事件:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
         _web_client.CancelAsync();
}

所以,如果我只是让下载完成,那么"成功MessageBox"将会显示。但是如果我在下载时关闭应用程序,则不会显示任何MessageBox,程序也不会崩溃,尽管我抛出了一个未经处理的异常。另一方面,文本文件被创建并填充测试字符串。

那为什么这不起作用?我应该如何处理File.Delete调用引发的可能异常?

(请注意,我使用的是WebClient.DownloadFileAsync)

提前致谢!

1 个答案:

答案 0 :(得分:0)

MessageBox.Show无效,因为应该是MessageBox所有者的表单已经被处理掉了。如果您将owner方法的Show参数设置为表单的当前实例,则会获得System.ObjectDisposedException。现在,您可以做的是:

private void _web_client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    if (e.Cancelled)
    {
        //Delete the file in here
        MessageBox.Show("Download cancelled!");
        File.Delete(@"path\to\partially\downloaded\file");
        this.Close(); 
    }
    else
    {
        MessageBox.Show("Download succeeded!"); // Works
    }
}



private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (_web_client.IsBusy)
    {
        e.Cancel = true;
        this._web_client.CancelAsync();
    }       
}