Checking network status in C#

后端 未结 7 1902
时光取名叫无心
时光取名叫无心 2020-11-30 05:05

How do I check that I have an open network connection and can contact a specific ip address in c#? I have seen example in VB.Net but they all use the \'My\' structure. Than

相关标签:
7条回答
  • 2020-11-30 05:53

    If you're interested in the HTTP status code, the following works fine:

    using System;
    using System.Net;
    
    class Program {
    
        static void Main () {
            HttpWebRequest req = WebRequest.Create(
                "http://www.oberon.ch/") as HttpWebRequest;
            HttpWebResponse rsp;
            try {
                rsp = req.GetResponse() as HttpWebResponse;
            } catch (WebException e) {
                if (e.Response is HttpWebResponse) {
                    rsp = e.Response as HttpWebResponse;
                } else {
                    rsp = null;
                }
            }
            if (rsp != null) {
                Console.WriteLine(rsp.StatusCode);
            }
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题