简体   繁体   中英

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.

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"){}

Maybe this or this might help. I don't think there's a direct command for images, but you could try using the FileExist method.

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. (Most likely a 404 Not Found error)

Its about the only way to do it from a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM