I have an application that I have created in two modes, installed and portable, and I need to obtain the serial number of the hard drive from which the program is running. In portable mode, it is simply that the binaries are copied to any folder and it is executed from there.
Until now the code had worked fine for me using WMI, but for two days it has been failing on two of the computers when I use it in portable mode. User accounts do not have administrative privileges.
The code I use is:
public static string GetDriveSerialNumber(string DriveLetter)
{
string Filt = string.Format("Win32_LogicalDisk.DeviceID=\"{0}:\"", DriveLetter);
System.Management.ManagementObject O = new System.Management.ManagementObject(Filt);
foreach (System.Management.PropertyData Prop in O.Properties)
{
if (Prop.Name == "VolumeSerialNumber")
{
return Prop.Value.ToString();
}
}
return null;
}
The exception I get is:
System.Management.ManagementException: Clase no válida
en System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
en System.Management.ManagementObject.Initialize(Boolean getObject)
en System.Management.ManagementBaseObject.get_Properties()
en enumdrvs.Program.GetDriveSerialNumber(String DriveLetter) en C:\workspace\Projects\PreviStorm\software\Host\playground\enumdrvs\Program.cs:línea 20
The line where the error occurs is foreach (System.Management.PropertyData Prop in O.Properties)
, which is when you ManagementObject
do the query, by listing it.
I have tried the following code to access the WMI, but I also get the error:
var driveQuery = new ManagementObjectSearcher("select * from Win32_DiskDrive");
foreach (ManagementObject d in driveQuery.Get())
{ ...etc... }
Has anyone else encountered this error? How can I solve it?
If I use right click "Run as administrator" I still have the problem.