C# - 完成文件下载后执行某些操作

时间:2016-10-08 09:32:40

标签: c# .net

所以,我正在尝试在下载完成时播放声音文件,但我不工作。在这里我的班级:

private String url = "http://download2098.mediafire.com/aut75nnjxh6g/34h69ha3ka375p4/Fed-Up+-+Virus+%28online-audio-converter.com%29.wav";
    private String file = @"C:\VirEDos\virus.wav";

    public Sounder()
    {
        download();
    }

    private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    {
        if (!e.Cancelled)
        {
            play();
        }
    }

    private void download()
    {
        using (WebClient webClient = new WebClient())
        {
            webClient.DownloadFile(url, file);
            webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Client_DownloadFileCompleted);
        }
    }

    private void play()
    {
        SoundPlayer player = new SoundPlayer(file);
        player.Load();
        player.Play();
    }

好吧,我添加了Imports和All Stuff,但为什么它不起作用?

1 个答案:

答案 0 :(得分:1)

无需使用WebClient.DownloadFileCompleted事件。这仅适用于异步下载。如果您按MSDN中所述的DownloadFile致电,则不会引发此事件:

  

每次异步文件下载操作时都会引发此事件   完成。通过调用来启动异步文件下载   DownloadFileAsync方法。

相反,你可以试试这个:

private String url = "http://download2098.mediafire.com/aut75nnjxh6g/34h69ha3ka375p4/Fed-Up+-+Virus+%28online-audio-converter.com%29.wav";
private String file = @"C:\VirEDos\virus.wav";

public Sounder()
{
    download();
    play();
}

private void download()
{
    using (WebClient webClient = new WebClient())
    {
        webClient.DownloadFile(url, file);
    }
}

private void play()
{
    SoundPlayer player = new SoundPlayer(file);
    player.Load();
    player.Play();
}