I got the following code chunk which is used to get the hard disk serial number given a partition. And I need to speed it up a bit, here is the slow part of the code :
//...
var partition = "Disk #0, Partition #0";//previously computed, hard coded here for clarity
var objSearcher = new ManagementObjectSearcher("root\\CIMV2", "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition + "'} WHERE ResultClass = Win32_DiskDrive");
var result = _objSearcher.Get();
var enumerator = result.GetEnumerator();
enumerator.MoveNext();//this takes 100ms
var diskSerial = (string)enumerator.Current.GetPropertyValue("SerialNumber");
It turns out that the line
enumerator.MoveNext();
takes 100ms, which is quite slow compared to the rest of the code. My best guess is that this call to MoveNext() is actually the moment when the ManagementBaseObject is built which takes quite long as the object has 51 properties. What motivates my guess is that I have already observed impressive speed ups when using regular WQL queries such as, for example :
"SELECT * FROM Win32_BaseBoard"// => MoveNext() is slow
by changing the query to:
"SELECT Model FROM Win32_BaseBoard"// => MoveNext() is fast
. So my best bet right now to speed things up would be to reduce the size of created ManagementBaseObject.
Thus my question is : Is there a way to introduce a 'SELECT' statement inside an "ASSOCIATORS OF .." query or to tweak or reformulate the query above such that it only queries the 'SerialNumber' property ? If not, are there other ways to speed up this code chunk ? Maybe without associators ? any proposition is welcome. Thanks !