c# 判斷網路地址是否存在

來源:互聯網
上載者:User

標籤:

方法一:網路地址存在,有可能可以訪問,也有可能不能訪問。此方法用來判斷地址存在。

 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# 判斷網路地址是否存在

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.