码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2015-06-26 19:27:46      阅读:156      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!