我有以下代码:
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
。
如果服务器上存在该文件,该如何下载?
由于您正在下载文件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);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句