vb.netnamespaceswmi.net-4.5

Why do I get an 'Invalid namespace' error when attempting to use WMI?


I need to get the serial number of a hard drive to serve as a unique ID for user identification purposes, but however the program is crashing when I attempt to access the serial number:

An unhandled exception of type 'System.Management.ManagementException' occurred in System.Management.dll

Additional information: Invalid namespace

I've looked around and there doesn't seem to be much on the issue; one website mentions that 'WMI is like Death Valley', and I'm inclined to agree on this.

The error is occurring at moHD.[Get]().

Why am I getting this error, and how can I fix it?

The code:

Public Function getSerial(ByVal strDrive As String) As String 'Get HD Serial Number
    If strDrive = "" OrElse strDrive Is Nothing Then
        strDrive = "C"
    End If
    Dim moHD As New ManagementObject("Win32_LogicalDisk.DeviceID=""" + strDrive + ":""")
    moHD.[Get]()
    Return moHD("VolumeSerialNumber").ToString()
End Function

Solution

  • Try passing the namespace where the Win32_LogicalDisk class is located. Check this sample :

    Public Function getSerial(ByVal strDrive As String) As String 'Get HD Serial Number
        If strDrive = "" OrElse strDrive Is Nothing Then
            strDrive = "C"
        End If
    
    Dim scope As New ManagementScope("\\.\root\cimv2")
    Dim path As New ManagementPath("Win32_LogicalDisk.DeviceID=""" + strDrive + ":""")
    Dim moHD  As New ManagementObject(scope, path, Nothing)
    moHD.[Get]()
    Return moHD("VolumeSerialNumber").ToString()
    End Function