测试 C# 中是否存在图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/192085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:26:48  来源:igfitidea点击:

Test to see if an image exists in C#

c#.netiis

提问by RedWolves

I am writing a diagnostic page for SiteScope and one area we need to test is if the connection to the file/media assets are accesible from the web server. One way I think I can do this is load the image via code behind and test to see if the IIS status message is 200.

我正在为 SiteScope 编写一个诊断页面,我们需要测试的一个方面是与文件/媒体资产的连接是否可以从 Web 服务器访问。我认为可以执行此操作的一种方法是通过隐藏代码加载图像并测试以查看 IIS 状态消息是否为 200。

So basically I should be able to navigate to within the site to a folder like this: /media/1/image.jpg and see if it returns 200...if not throw exception.

所以基本上我应该能够在站点内导航到这样的文件夹:/media/1/image.jpg 并查看它是否返回 200...如果不抛出异常。

I am struggling to figure out how to write this code.

我正在努力弄清楚如何编写这段代码。

Any help is greatly appreciated.

任何帮助是极大的赞赏。

Thanks

谢谢

采纳答案by Greg Dean

Just use HEAD. No need to download the entire image if you don't need it. Here some boilerplate code.

只需使用头。如果您不需要,则无需下载整个图像。这里有一些样板代码。

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("url");
request.Method = "HEAD";

bool exists;
try
{
    request.GetResponse();
    exists = true;
}
catch
{
   exists = false;
}

回答by user25519

I'd look into an HttpWebRequest instead - I think the previous answer will actually download data, whereas you should be able to get the response without data from HttpWebRequest.

我会改为查看 HttpWebRequest - 我认为之前的答案实际上会下载数据,而您应该能够在没有来自 HttpWebRequest 的数据的情况下获得响应。

http://msdn.microsoft.com/en-us/library/456dfw4f.aspxuntil step #4 should do the trick. There are other fields on HttpWebResponse for getting the numerical code if needs be...

http://msdn.microsoft.com/en-us/library/456dfw4f.aspx直到第 4 步应该可以解决问题。如果需要,HttpWebResponse 上还有其他字段可用于获取数字代码...

hth Hyman

Hyman

回答by beno

I've used something like this before, but there's probably a better way:

我以前使用过类似的东西,但可能有更好的方法:

try
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://somewhere/picture.jpg");
    request.Credentials = System.Net.CredentialCache.DefaultCredentials;
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    myImg.ImageUrl = "http://somewhere/picture.jpg";
}
catch (Exception ex)
{
    // image doesn't exist, set to default picture
    myImg.ImageUrl = "http://somewhere/default.jpg";
}

回答by Anjisan

You might want to also check that you got an OK status code (ie HTTP 200) and that the mime type from the response object matches what you're expecting. You could extend that along the lines of,

您可能还想检查您是否获得了 OK 状态代码(即 HTTP 200)以及响应对象中的 mime 类型是否与您期望的匹配。你可以沿着以下路线扩展它,

public bool doesImageExistRemotely(string uriToImage, string mimeType)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriToImage);
    request.Method = "HEAD";

    try
    {
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        if (response.StatusCode == HttpStatusCode.OK && response.ContentType == mimeType)
        {
            return true;
        }
        else
        {
            return false;
        }   
    }
    catch
    {
        return false;
    }
}

回答by Anjisan

You have to dispose of the HTTPWebResponse object, otherwise you will have issues as I have had...

您必须处理 HTTPWebResponse 对象,否则您将遇到我遇到的问题...

    public bool DoesImageExistRemotely(string uriToImage)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriToImage);

            request.Method = "HEAD";

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {

                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (WebException) { return false; }
            catch
            {
                return false;
            }
    }

回答by jhamm

If you are getting an exception during the request like "The remote server returned an error: (401) Unauthorized.",

如果您在请求过程中遇到异常,例如“远程服务器返回错误:(401) 未经授权。”,

This can be resolved by adding the following line

这可以通过添加以下行来解决

request.Credentials = new NetworkCredential(username, password);

Question and answer added to this questions from check if image exists on intranet.

检查 Intranet 上是否存在图像中添加到此问题的问答。

回答by Paulos02

If url exists like http:\server.myImageSite.com the answer is false too only if imageSize > 0 is true.

如果 url 像 http:\server.myImageSite.com 这样存在,那么只有当 imageSize > 0 为真时,答案也是假的。

  public static void GetPictureSize(string url, ref float width, ref float height, ref string err)
  {
    System.Net.HttpWebRequest wreq;
    System.Net.HttpWebResponse wresp;
    System.IO.Stream mystream;
    System.Drawing.Bitmap bmp;

    bmp = null;
    mystream = null;
    wresp = null;
    try
    {
        wreq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
        wreq.AllowWriteStreamBuffering = true;

        wresp = (HttpWebResponse)wreq.GetResponse();

        if ((mystream = wresp.GetResponseStream()) != null)
            bmp = new System.Drawing.Bitmap(mystream);
    }
    catch (Exception er)
    {
        err = er.Message;
        return;
    }
    finally
    {
        if (mystream != null)
            mystream.Close();

        if (wresp != null)
            wresp.Close();
    }
    width = bmp.Width;
    height = bmp.Height;
}

public static bool ImageUrlExists(string url)
{

    float width = 0;
    float height = 0;
    string err = null;
    GetPictureSize(url, ref width, ref height, ref err);
    return width > 0;
}