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.
The cause of the problem was that the WMI infrastructure had become corrupted and needed to be repaired with the help of the network administration colleague.
A tool that I found useful for testing was WMI Code Creator , which can be downloaded from here -> link . This tool allows you to generate code in C# to access specific parameters, it is a good help for those cases.
From a command line, with administrator privileges, with
winmgmt /verifyrepository
you can check the integrity of the WMI data, in my case it said OK, but it was not entirely true because all the objects ofWin32_DiskDrive
.It was necessary to force the recovery using:
The program would freeze on launch after doing these steps, but after rebooting the computer, voila, everything back to normal.