首页 > Windows开发 > 详细

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

时间:2015-06-26 19:24:32      阅读:226      评论:0      收藏:0      [点我收藏+]

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

 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         }

 

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

原文:http://www.cnblogs.com/guohu/p/4602838.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!