using System.Net.NetworkInformation; //... bool isConnected = false; try { Ping ping = new Ping(); PingReply reply = ping.Send("www.google.com"); if(reply.Status == IPStatus.Success) { isConnected = true; } } catch (Exception ex) { // handle exception } if (isConnected) { Console.WriteLine("You are connected to the internet."); } else { Console.WriteLine("You are not connected to the internet."); }
using System.Management; //... bool isConnected = false; ManagementEventWatcher watcher = new ManagementEventWatcher(); WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2"); watcher.Query = query; watcher.Start(); ManagementBaseObject eventObj; do { eventObj = watcher.WaitForNextEvent(); if (eventObj.Properties["TargetInstance"].ToString().Contains("USB VID_0403&PID_6001")) { isConnected = true; } } while (!isConnected); watcher.Stop(); if (isConnected) { Console.WriteLine("The USB device is connected."); } else { Console.WriteLine("The USB device is not connected."); }In this example, the code uses the "ManagementEventWatcher" class from the "System.Management" package to monitor for any changes in the device configuration and check if a specific USB device is connected. The USB device is identified by its Vendor ID (VID) and Product ID (PID). Package/Library: System.Net.NetworkInformation, System.Management.