Is there a way to get a list of disabled/enabled network interfaces in C#

末鹿安然 提交于 2019-12-20 01:45:51

问题


I am programming a little script to change the IPv4 address of a specific Wireless80211 or Ethernet network interface. So far everything is working fine. The script sets the IPv4 with the command prompt and netsh (to control it with C# I use System.Diagnostics). I want to add the feature, that the script disables or enables all Wireless80211 and Ethernet network interfaces (without a specific one) which you can find in "Control Panel>Network and Internet>Network Connections".

The script is mainly used for ArtNet to DMX to automatically prepare everything to use ArtNet (for people, which do not know anything of the Control Panel and to automate the workflow). I have already tried it with the System.Net.NetworkInformation namespace, but I have only found a way to get enabled network interfaces. As soon as I disable an interface System.Net.NetworkInformation does not show this interface.


回答1:


I wasn't aware that NetworkInterface.GetAllNetworkInterfaces() didn't return disabled interfaces.

Anyway, you could try using the WMI api via System.Management.dll that's available in the .NET framework (you must add this reference to your project), I did a test and it allows you to interact even with disabled network interfaces.

The following example give you an idea of how to work with WMI via this api, I pretty much extracted it from the documentation:

using System;
using System.Management;
...
void ListNetworkAdapters()
{
    var query = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter");

    using (var searcher = new ManagementObjectSearcher(query))
    {
        var queryCollection = searcher.Get();

        foreach (var m in queryCollection)
        {
            Console.WriteLine("ServiceName : {0}", m["Name"]);
            Console.WriteLine("MACAddress : {0}", m["Description"]);
            Console.WriteLine();
        }

        Console.ReadLine();
    }
}

The documentation can be found here: https://docs.microsoft.com/en-us/windows/desktop/cimwin32prov/win32-networkadapter




回答2:


NetworkInterface.GetAllNetworkInterfaces()

Then check the OperationalStatus property

https://docs.microsoft.com/en-us/dotnet/api/system.net.networkinformation.networkinterface?view=netframework-4.7.2



来源:https://stackoverflow.com/questions/54485908/is-there-a-way-to-get-a-list-of-disabled-enabled-network-interfaces-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!