How to disable (or reset) a network adapter programmatically in C#
I need to disable a network adapter programmatically using C# (.NET 2.0) on Windows XP Embedded.
Background Reason: After installing a Bluetooth stack on the PC, the Bluetooth PAN adapter blocks the Bluetooth manager program (that runs in the system tray). If I disable the Bluetooth PAN then the Bluetooth mana开发者_如何学Pythonger works fine.
This issue is happening only on Windows XP Embedded machines.
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.
精彩评论