c# Store应用程序检查URL中的图片是否可用

本文关键字:是否 Store 应用程序 检查 URL | 更新日期: 2023-09-27 18:19:17

我正在制作一个包含图片的c#商店应用程序。我从一个网站获取图片,例如:http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG

我有2张图片,1张是实际产品的图片。1是一个没有可用图像的图像。现在我想检查给定的URL后面是否有图片,如果没有,我想加载没有可用图像的图像。

我得到一个对象product,它包含itemnumber, description和imagepath。此时,我只需执行以下操作:

var url = "http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG";
Product p = new product (123, "productdescription", url);

if (url//如果没有给出结果){p.url = imgpath2}//没有图像的文件路径

我怎样才能使一个简单的检查,如果给定的url包含图片,或会给我一个"网页不可用"/没有内容可用的错误?提前谢谢。

注意*我正在与visual studio 2013工作,我正在构建一个c#商店应用程序。

c# Store应用程序检查URL中的图片是否可用

无需下载整张图片,只需使用HEAD:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("url");
request.Method = "HEAD";
bool exists;
try
{
    request.GetResponse();
    exists = true;
}
catch
{
   exists = false;
}

要了解更多信息,您可以查看这篇文章,以帮助您解决问题:


[Update: If you want make call asynchronous…]

// Initialize your product with the 'blank' image
Product p = new Product(123, "productdescription", imgpath2);
// Initialize the request
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("url");
request.Method = "HEAD";
// Get the response async
Task<WebResponse> response = request.GetResponseAsync();
// Get the response async
response.AsAsyncAction().Completed += (a, b) =>
    {
        // Assign the proper image, if exists, when the task is completed
        p.URL = url;
    };

试试这个:

    var url = "http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG";
    if(File.Exists(url)){
         Product p = new product (123, "productdescription", url);
    }
    else{
         Product p = new product (123, "productdescription", imgpath2);
    }

如果文件存在则返回true,如果不存在则返回false。

如果你想知道如何找出一个url是否给你任何响应,你也可以看看前面的主题:如何检查URL是否存在/是否有效?