下载文件(如果它存在于服务器上)

时间:2013-10-11 19:02:11

标签: c# asp.net download

我有这段代码:

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

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

1 个答案:

答案 0 :(得分: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);
    }

}