AStopher
AStopher

Reputation: 4551

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

Upvotes: -1

Views: 10194

Answers (2)

Mohammad Naushad M
Mohammad Naushad M

Reputation: 66

Restoring of WMI resolved the issue for me :

  1. open the Command Prompt as Administrator:
  2. Run the following commands one at a time: winmgmt /verifyrepository winmgmt /salvagerepository winmgmt /resetrepository
  3. Restart the computer.

Upvotes: 0

RRUZ
RRUZ

Reputation: 136431

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

Upvotes: 3

Related Questions