C# 判断网站是否能访问或者断链

最近有位朋友说他有很多网址,可能有些已经过期或者不能访问了。自己去一个一个点可以,但又很麻烦!

再过一段时间又要去检查一次,每次都这样就不方便了! 于是就做了个小程序给帮他检测一下。

以下做了一个例子作为参考:

using System.Net;


    public bool CheckUrlVisit(string url) 
    {       
        try
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            if (resp.StatusCode == HttpStatusCode.OK)
            {
          resp.Close(); 
return true; } } catch (WebException webex) { return false; } return false; } string[] links = { "http://www.baidu.com", "http://www.google.com", "http://www.chinabuffetflora.com" }; foreach (string link in links) { HttpContext.Current.Response.Write( link+" : "+CheckUrlVisit(link)+" <br>"); }

测试结果:

http://www.baidu.com : True 
http://www.google.com : True 
http://www.chinabuffetflora.com : False 

原文地址:https://www.cnblogs.com/junny/p/2745978.html