[英]How can I check if an Image exists at http://someurl/myimage.jpg in C#/ASP.NET
How can I check if an Image exists at http://someurl/myimage.jpg in C#/ASP.NET It seems like there ought to be a method to check for this -- but I cannot find one. 如何检查图像是否存在于C#/ ASP.NET中的http://someurl/myimage.jpg似乎应该有一种方法来检查这个 - 但我找不到一个。
I found this , but it doesn't really answer the question. 我找到了这个 ,但它并没有真正回答这个问题。
This code should work: 这段代码应该有效:
private static bool UrlExists(string url)
{
try
{
new System.Net.WebClient().DownloadData(url);
return true;
}
catch (System.Net.WebException e)
{
if (((System.Net.HttpWebResponse)e.Response).StatusCode == System.Net.HttpStatusCode.NotFound)
return false;
else
throw;
}
}
您可以尝试使用System.Net.WebRequest
向该URL发送“HEAD”请求并检查响应以查看该文件是否存在 - 这应该可以完成工作,而无需尝试下载它。
string fileextension = Path.GetExtension(filename);
if (fileextension.ToLower() == ".png" || fileextension.ToLower() == ".jpg" || fileextension.ToLower() == ".jpeg" || fileextension.ToLower() == ".gif" || fileextension.ToLower() == ".bmp"){}
You could use a System.Net.WebClient.DownloadFile function to try to load the image from the URL and see if you get an error. 您可以使用System.Net.WebClient.DownloadFile函数尝试从URL加载图像,看看是否收到错误。 (Most likely a 404 Not Found error) (很可能是404 Not Found错误)
Its about the only way to do it from a URL. 它是关于从URL执行此操作的唯一方法。 The System.IO namespace and all the functions in there are intended for files on a local machine or a network, so they would be useless to you in this situation. System.IO命名空间及其中的所有功能都是针对本地计算机或网络上的文件,因此在这种情况下它们对您没用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.