標籤:
方法一:網路地址存在,有可能可以訪問,也有可能不能訪問。此方法用來判斷地址存在。
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 try13 {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 try23 {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 catch11 {12 return false;13 }14 }
c# 判斷網路地址是否存在