问题
I'm trying to detect when an Ethernet cable is plugged-in or unplugged but i have some probleme and i don't know if i'm doing this good or not.
I'm using NetworkChange.NetworkAddressChanged
to detect when the network change
and then NetworkInterface.GetAllNetworkInterfaces()
for checking if Ethernet connexion is available or not with the property .OperationalStatus
.
But when i search for the Ethernet connexion in all the network interfaces, it return me what i'm looking for, but it always return me the Bluetooth connection with it.
Here is the code :
public Form1()
{
InitializeComponent();
NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(AddressChangedCallback);
Console.ReadLine();
}
static void AddressChangedCallback(object sender, EventArgs e)
{
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface myInterface in adapters)
{
//if (n.Description.ToLower().Contains("ethernet")){
//if (n.NetworkInterfaceType.ToString().ToLower().Contains("ethernet")){
IPInterfaceProperties properties = n.GetIPProperties();
if (myInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
Console.WriteLine(myInterface.Description + " ........... : " + myInterface.OperationalStatus);
Console.WriteLine("NetworkInterfaceType : " + myInterface.NetworkInterfaceType);
}
}
}
At the beginning, i was trying to check the name of the connection and looks if contains the "Ethernet" word, but it appears (if i'm not wrong) sometimes the connection name does not contain "Ethernet".
Do you have some tips for always bring the good connection (without the bluetooth)?
Am i wrong in my approach?
I'm testing it on a Surface Pro 3... but maybe i have the Bluetooth problem because of that? Despite that, i need it to work even on device like this.
回答1:
This links shows how to do it with Powershell, but one of the cases uses WMI.
http://www.powershellmagazine.com/2013/04/04/pstip-detecting-wi-fi-adapters/
And this links shows a interesting property that can help sometimes:
https://msdn.microsoft.com/en-us/library/aa394217(v=vs.85).aspx
GatewayCostMetric
Data type: uint16 array
Access type: Read-only Array
of integer cost metric values (ranging from 1 to 9999) to be used in calculating the fastest, most reliable, or least resource-intensive routes. This argument has a one-to-one correspondence with the DefaultIPGateway property.
回答2:
This can be done by checking its operational status as:
foreach (System.Net.NetworkInformation.NetworkInterface net in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
{
if (net.OperationalStatus ==
System.Net.NetworkInformation.OperationalStatus.Up)
Console.WriteLine("N/w connected");
else
Console.WriteLine("N/w not connected");
}
来源:https://stackoverflow.com/questions/32884367/detect-when-ethernet-cable-is-plugged