程序需要用管理员的身份运行,使用WMI(Windows Management Instrumentation)
- 使用ManagementObjectSearcher对象获取适配器信息
- 使用ManagementObject的InvokeMethod方法执行相应操作
-
static void Main(string[] args){Console.ForegroundColor = ConsoleColor.Yellow;Console.WriteLine("本地连接名称:Realtek Gaming GbE Family Controller");Console.WriteLine("无线连接名称:Intel(R) Wi-Fi 6 AX201 160MHz");Console.ForegroundColor = ConsoleColor.Green;string wx = "Intel(R) Wi-Fi 6 AX201 160MHz";string ben = "Realtek Gaming GbE Family Controller";string str = "编号1:无线开,本地关\r\n编号2:无线关,本地开";Console.WriteLine(str);Console.ForegroundColor = ConsoleColor.White;while (true){bool wxState = false;bool benState = false;string num = Console.ReadLine();NetManager(num, wx, ben, ref wxState, ref benState);Console.WriteLine("无线状态:" + wxState + " 本地状态:" + benState);Console.ReadKey();}}/// <summary>/// 获取网络/// </summary>/// <param name="num">标识</param>/// <param name="wx">无线网络名称</param>/// <param name="ben">本地网络名称</param>/// <param name="wxState">返回执行状态</param>/// <param name="benState">返回执行状态</param>public static void NetManager(string num,string wx,string ben, ref bool wxState, ref bool benState){string manage = "SELECT * From Win32_NetworkAdapter";// WHERE Name='本地连接'ManagementObjectSearcher searcher = new ManagementObjectSearcher(manage);ManagementObjectCollection collection = searcher.Get();if (num == "1"){foreach (ManagementObject obj in collection){if (obj["Name"].ToString() == wx){wxState= EnableLocalNetwork(obj);}else if (obj["Name"].ToString() == ben){benState= DisableLocalNetwork(obj);}}}else if (num == "2"){foreach (ManagementObject obj in collection){if (obj["Name"].ToString() == wx){wxState= DisableLocalNetwork(obj);}else if (obj["Name"].ToString() == ben){benState= EnableLocalNetwork(obj);}}} }/// <summary>/// 禁用网卡/// </summary>5/// <param name="adapter">网卡对象</param>/// <returns></returns>public static bool DisableLocalNetwork(ManagementObject adapter){ if (adapter == null) return false;ManagementBaseObject inParams = adapter.GetMethodParameters("Disable");ManagementBaseObject outParams = adapter.InvokeMethod("Disable", inParams, null);uint resultCode = (uint)outParams["returnValue"];return resultCode == 0;}/// <summary>/// 启用网卡/// </summary>/// <param name="adapter">网卡对象</param>/// <returns></returns>public static bool EnableLocalNetwork(ManagementObject adapter){ if (adapter == null) return false;ManagementBaseObject inParams = adapter.GetMethodParameters("Enable");ManagementBaseObject outParams = adapter.InvokeMethod("Enable", inParams, null);uint resultCode = (uint)outParams["returnValue"];return resultCode == 0;}}