windows 以编程方式启用/禁用连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3053372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Programmatically Enable / Disable Connection
提问by pistacchio
on Windows 7 I can enable and disable connections via the Network Connections Manager panel (in system settings).
在 Windows 7 上,我可以通过网络连接管理器面板(在系统设置中)启用和禁用连接。
How can I do this programmatically in C#? Thanks
如何在 C# 中以编程方式执行此操作?谢谢
回答by Tim Lloyd
You can achieve this in C# by leveraging WMI and the Win32_NetworkAdapter WMI class. The Win32_NetworkAdapter class has Enable and Disable methods which can be executed on a selected network interface.
您可以在 C# 中通过利用 WMI 和 Win32_NetworkAdapter WMI 类来实现这一点。Win32_NetworkAdapter 类具有可以在选定的网络接口上执行的 Enable 和 Disable 方法。
An example of usage can be found here:
可以在此处找到使用示例:
link not available, but archived at:
链接不可用,但存档于:
Briefly, steps to do this are:
简而言之,执行此操作的步骤是:
Generate a wrapper for the class from VS command prompt
mgmtclassgen Win32_NetworkAdapter /L CS -p NetworkAdapter.cs
Stepping through the adapters:
SelectQuery query = new SelectQuery("Win32_NetworkAdapter", "NetConnectionStatus=2"); ManagementObjectSearcher search = new ManagementObjectSearcher(query); foreach(ManagementObject result in search.Get()) { NetworkAdapter adapter = new NetworkAdapter(result); // Identify the adapter you wish to disable here. // In particular, check the AdapterType and // Description properties. // Here, we're selecting the LAN adapters. if (adapter.AdapterType.Contains("Ethernet 802.3")) { adapter.Disable(); } }
从 VS 命令提示符生成类的包装器
mgmtclassgen Win32_NetworkAdapter /L CS -p NetworkAdapter.cs
逐步完成适配器:
SelectQuery query = new SelectQuery("Win32_NetworkAdapter", "NetConnectionStatus=2"); ManagementObjectSearcher search = new ManagementObjectSearcher(query); foreach(ManagementObject result in search.Get()) { NetworkAdapter adapter = new NetworkAdapter(result); // Identify the adapter you wish to disable here. // In particular, check the AdapterType and // Description properties. // Here, we're selecting the LAN adapters. if (adapter.AdapterType.Contains("Ethernet 802.3")) { adapter.Disable(); } }