1

我有这个代码:

WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri("http://MySite.com/Desktop/Pics.png"), 
    @"c:\users\Windows\desktop\DesktopsPics\Desktop.png");

我的程序将下载一个.png每天下载一张图片作为“每日图片”在一个文件夹中!所以,当用户点击一个按钮时,如果“每日图片”已经存在于服务器中,程序就会下载这个文件。

我可以用上面的代码做到这一点,但是,如果Pic.Png服务器中不存在,我的程序会抛出一个错误。它下载一个.html文件,内容为404 not found.

如果该文件存在于服务器上,我如何下载该文件?

4

1 回答 1

0

由于您正在下载 Async 文件,因此您需要为下载完成添加一个事件处理程序。然后您可以检查 arg 是否有错误。

尝试这个:

static void Main(string[] args)
{
    WebClient client = new WebClient();
    client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted);

    string fileName = Path.GetTempFileName();
    client.DownloadFileAsync(new Uri("https://www.google.com/images/srpr/logo11w.png"), fileName, fileName);

    Thread.Sleep(20000);
    Console.WriteLine("Done");
}

private static void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
{
    if (e.Error != null)
    {
            // inspect error message for 404
        Console.WriteLine(e.Error.Message);
        if (e.Error.InnerException != null)
            Console.WriteLine(e.Error.InnerException.Message);
    }
    else
    {
        // We have a file - do something with it
        WebClient client = (WebClient)sender;

        // display the response header so we can learn
        foreach(string k in client.ResponseHeaders.AllKeys)
        {
            Console.Write(k);
            Console.WriteLine(": {0}", client.ResponseHeaders[k]);
        }

        // since we know it's a png, let rename it
        FileInfo temp = new FileInfo((string)e.UserState);
        string pngFileName = Path.Combine(Path.GetTempPath(), "DesktopPhoto.png");
        if (File.Exists(pngFileName))
            File.Delete(pngFileName);

        File.Move((string)e.UserState, pngFileName);  // move to where ever you want
        Process.Start(pngFileName);
    }

}
于 2013-10-12T01:08:00.080 回答