c# 判断网络地址是否存在

方法一:网络地址存在,有可能可以访问,也有可能不能访问。此方法用来判断地址存在。

 1  static bool UrlIsExist(String url)
 2         {
 3             System.Uri u = null;
 4             try
 5             {
 6                 u = new Uri(url);
 7             }
 8             catch { return false; }
 9             bool isExist = false;
10             System.Net.HttpWebRequest r = System.Net.HttpWebRequest.Create(u) as System.Net.HttpWebRequest;
11             r.Method = "HEAD";
12             try
13             {
14                 System.Net.HttpWebResponse s = r.GetResponse() as System.Net.HttpWebResponse;
15                 if (s.StatusCode == System.Net.HttpStatusCode.OK)
16                 {
17                     isExist = true;
18                 }
19             }
20             catch (System.Net.WebException x)
21             {
22                 try
23                 {
24                     isExist = ((x.Response as System.Net.HttpWebResponse).StatusCode != System.Net.HttpStatusCode.NotFound);
25                 }
26                 catch { isExist = (x.Status == System.Net.WebExceptionStatus.Success); }
27             }
28             return isExist;
29         }

方法二:地址是否有效,即是网络连接地址是否正常显示。地址有可能存在,也有可能不存在,能正常显示则说明地址是有效的,反正则是无效的。

 1         static bool UrlIsExist(string URL)
 2         {
 3             try
 4             {
 5                 System.Net.WebRequest request = System.Net.WebRequest.Create(URL);
 6                 request.Timeout = 10000;
 7                 System.Net.WebResponse response = request.GetResponse();
 8                 return true;
 9             }
10             catch
11             {
12                 return false;
13             }
14         }

 程序员的基础教程:菜鸟程序员

转载于:https://www.cnblogs.com/guohu/p/4602838.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值