How to disable (or reset) a network adapter programmatically in C#

依然范特西╮ 提交于 2019-12-01 17:42:27

try this:

netsh interface set interface "YOUR_ADAPTOR" DISABLED

netsh interface set interface "YOUR_ADAPTOR" DISABLED

NOTE: Note sure about XP, but in Windows Vista / Windows 7, this will only work on a command prompt run with administrator privileges ("Run as Administrator" option).

If you want to use the name shown in device manager it is probably going to be easier to use WMI. A query

SELECT * FROM Win32_NetworkAdpater WHERE NName='name from device mnanager'

will select a WMI object with a Disable method.

Something like this given a device name "Realtek PCIe GBE Family Controller":

var searcher = new ManagementObjectSearcher("select * from win32_networkadapter where Name='Realtek PCIe GBE Family Controller'");
var found = searcher.Get();
var nicObj = found.First() as ManagementObject; // Need to cast from ManagementBaseObject to get access to InvokeMethod.

var result = (uint)nicObj.InvokeMethod("Disable"); // 0 => success; otherwise error.

NB. like Netsh this will require elevation to perform the disable (but not for the query).

It depends on what you are trying to disable. If you are trying to disable LAN network interfaces then the only possibility on XP-machines (as far as I know) to do this programatically is using devcon.exe (a program that is like the device manager commandlline utility).

The syntax would be

devcon disable *hardware ID of your adapter*

You get the HWID (along with many other details) with

wmic NIC

or if you have access to Powershell on your XP-machine you could use that because you can filter ir nicely there. wmic NIC does nothing else than output the results of Select * From Win32_NetworkAdapter

gwmi win32_networkAdapter | select Name, PNPDeviceID | where {$_.Name -eq "*your adapter name*"}

or

gwmi -query "select Name, PNPDeviceID from Win32_Networkadapter" | where {$_.Name -eq "*your adapter name*"}

The problem with using WMI to disable or enable your adapters is that it is up to the device driver to implement the Disable() and Enable() Methods so you cant really rely on it working.

I dont know how well netsh works for bluetooth adapters and other devices but I would definitely recommend you try that because it's much simpler of a solution than using devcon and having to look up the HWID.

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