【问题标题】:Test to see if an image exists in C#测试以查看 C# 中是否存在图像
【发布时间】:2008-10-10 16:13:53
【问题描述】:

我正在为 SiteScope 编写诊断页面,我们需要测试的一个区域是是否可以从 Web 服务器访问到文件/媒体资产的连接。我认为我可以做到这一点的一种方法是通过后面的代码加载图像并测试 IIS 状态消息是否为 200。

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

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

非常感谢任何帮助。

谢谢

【问题讨论】:

  • 如果我想用http://localhost/homepage 之类的 URL 测试一个页面,看看这个页面中是否有任何丢失的图像?我最初的想法是使用HttpWebRequest 读取页面,获取响应然后查看内容,对于每个 元素,生成另一个请求。有什么不同的想法吗?

标签: c# .net iis


【解决方案1】:

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

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

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

【讨论】:

  • 此方法是否可以应用于文件夹,如果它们存在或不存在?
  • @JL,什么文件夹?文件系统??
  • 这不是对每个文件都返回 true,而不仅仅是图像吗?
【解决方案2】:

您可能还想检查您是否获得了 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;
    }
}

【讨论】:

  • 我想补充一点,如果您在 HttpWebResponse 请求周围添加 using 语句......您将确保您的应用在连续三个请求后不会挂起。使用 BackgroundWorker 时可能会出现这种情况。 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { //逻辑到这里 }
  • 如果你得到任何ProtocolError(远程服务器返回错误:(500)内部服务器错误。)更改:request.Method="GET";
  • 要为图像指定的 mimeType 是什么?
【解决方案3】:

您必须处理 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;
            }
    }

【讨论】:

    【解决方案4】:

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

    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";
    }
    

    【讨论】:

      【解决方案5】:

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

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

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

      问题和答案来自check if image exists on intranet

      【讨论】:

        【解决方案6】:

        如果 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;
        }
        

        【讨论】:

          【解决方案7】:

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

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

          第 杰克

          【讨论】:

          • 它唯一会下载的是响应头,根据定义,它是“响应”
          猜你喜欢
          • 2021-11-05
          • 2013-07-16
          • 2012-02-16
          • 2021-09-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多