How to check the Internet connection with .NET, C#, and WPF

后端 未结 7 1526
陌清茗
陌清茗 2020-11-30 04:51

I am using .NET, C# and WPF, and I need to check whether the connection is opened to a certain URL, and I can\'t get any code to work that I have found on the Internet.

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 05:29

    I think this will be more accurate when it comes windows applications, Windows form or WPF apps, Instead of using WebClient or HttpWebRequest,

    public class InternetChecker
    {
        [System.Runtime.InteropServices.DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
    
        //Creating a function that uses the API function...
        public static bool IsConnectedToInternet()
        {
            int Desc;
            return InternetGetConnectedState(out Desc, 0);
        }
    
    }
    

    While calling write

    if(InternetCheckerCustom.CheckNet())
    {
      // Do Work 
    }
    else
    {
      // Show Error MeassgeBox 
    }
    

提交回复
热议问题