Search code examples
c#wmi

Trouble passing a parameter for ManagementObject query in c#


This is the code that I have for my query:

public String getDriveID()
{
    String wow = @"win32_logicaldisk.deviceid=\" + @driveID;

    ManagementObject disk = new ManagementObject(wow);
    disk.Get();
    Console.WriteLine(disk["Name"]);
    return disk["Name"].ToString();
}

And this is what creates the driveID String that the method uses:

DriveInfo dInfo = therehasgottobeanotherway[driveList.SelectedIndex];

if (dInfo.IsReady) {
    diskWMI dwmi = new diskWMI(dInfo.Name);
}

If you're not familiar with the DriveInfo class, the Name attribute returns the name of the drive, for example c:\

I found this code online that does the EXACT same thing I'm trying to do, but I always get an error when I'm trying to use it:

ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
disk.Get();
Console.WriteLine(disk["VolumeName"]);
Console.ReadLine();

I bet there is a formatting error happening but I can't figure out what to change.

I'm trying to pass in a drives name where it has deviceid=


Solution

  • public string GetHDDSerialNumber(string drive)
    {
        //check to see if the user provided a drive letter
        //if not default it to "C"
        if (drive == "" || drive == null)
        {
            drive = "C";
        }
        //create our ManagementObject, passing it the drive letter to the
        //DevideID using WQL
        ManagementObject disk = new ManagementObject("Win32_LogicalDisk.DeviceID=\"" + drive + ":\"");
        //bind our management object
        disk.Get();
        //return the serial number
        return disk["VolumeSerialNumber"].ToString();
    }
    

    or for your existing example this will work for you

    String drive = "c";
    ManagementObject disk = new ManagementObject("Win32_LogicalDisk.DeviceID=\"" + drive + ":\"");
    disk.Get();
    Console.WriteLine(disk["VolumeName"]);
    Console.ReadLine();