Search code examples
vb.netdevice-manager

In vb.net how do you read non-hidden devices as seen in device manager Network Adaptor section


I am trying to read the network adapters as seen here at the moment I am using the code I found online

Sub Main()
    Dim path As ManagementPath = New ManagementPath()
    path.Server = "."
    path.NamespacePath = "root\CIMV2"
    Dim scope As ManagementScope = New ManagementScope(path)
    Dim query As ObjectQuery = New ObjectQuery("SELECT * FROM Win32_NetworkAdapter")
    Dim searcher As ManagementObjectSearcher = New ManagementObjectSearcher(scope, query)
    Dim queryCollection As ManagementObjectCollection = searcher.Get()
    Dim m As ManagementObject
    For Each m In queryCollection
            Console.WriteLine("Device Name : {0}", m("Name"))
    Next
    Console.ReadLine()
End Sub

Right now I am seeing a list of devices that include those 4, but also a bunch of hidden devices and what looks like devices that are not connected anymore. How do I refine my search to only show what the device manager shows by default?


Solution

  • Found my answer on another forum, but cannot find the link again. Here is the answer:

      Dim moIP As ManagementObject
        Dim myNet = New ManagementObjectSearcher _
        ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") 
        Dim CountIncrement As Int16 = 1
        For Each moIP In myNet.Get            
            Console.WriteLine()
            'find device with  MAC Address
            If CStr(moIP("MACAddress")) = "00:11:22:33:44:55" Then
              'code here
            End If
        Next
    

    Edit: inside the for loop, these checks can also be done for finding information about connected devices.

            Console.WriteLine("Device Name : {0}", moIP("Caption"))
            Console.WriteLine("Service Name : {0}", moIP("ServiceName"))
            Console.WriteLine("Description Name : {0}", moIP("Description"))
            Console.WriteLine("MAC : {0}", moIP("MACAddress"))
            Console.WriteLine(moIP("IPAddress")(0))