Any way to turn the “internet off” in windows using c#?

前端 未结 5 1328
误落风尘
误落风尘 2020-11-28 05:17

I am looking for pointers towards APIs in c# that will allow me to control my Internet connection by turning the connection on and off.

I want to write a little con

5条回答
  •  野性不改
    2020-11-28 05:26

    This is what I am currently using (my idea, not an api):

    System.Diagnostics;    
    
    void InternetConnection(string str)
    {
        ProcessStartInfo internet = new ProcessStartInfo()
        {
            FileName = "cmd.exe",
            Arguments = "/C ipconfig /" + str,
            WindowStyle = ProcessWindowStyle.Hidden
        };  
        Process.Start(internet);
    }
    

    Disconnect from internet: InternetConnection("release");
    Connect to internet: InternetConnection("renew");

    Disconnecting will just remove the access to internet (it will show a caution icon in the wifi icon). Connecting might take five seconds or more.

    Out of topic:
    In any cases you might want to check if you're connected or not (when you use the code above), I better suggest this:

    System.Net.NetworkInformation;
    
    public static bool CheckInternetConnection()
    {
       try
       {
           Ping myPing = new Ping();
           String host = "google.com";
           byte[] buffer = new byte[32];
           int timeout = 1000;
           PingOptions pingOptions = new PingOptions();
           PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
                return (reply.Status == IPStatus.Success);
        }
        catch (Exception)
        {
           return false;
        }
    }
    

提交回复
热议问题