I need to retrieve the name of drive where Windows is installed. Best way I found to do it is via registry, since WMI is very slow for this specific query.
string diskdrive = Registry.GetValue(@"HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\Scsi\Scsi Port 0\Scsi Bus 0\Target Id 0\Logical Unit Id 0", "Identifier", null);
Which returns : INTEL SSDSCKKF512H6 LBF
While this works perfect form my system, "Target Id" seems to have different digit identifier for other system. how would I go about to detect the specific target ID (maybe detect it by using part of the registry subkey string, somehow). Not even sure this will do the job for other type of disks (Nvme or IDE). If there is a better way to do this without WMi query.
Thanks in advance
Found something from CMD:
REG QUERY "HKLM\HARDWARE\DEVICEMAP\Scsi\Scsi Port 0\Scsi Bus 0\Target Id 0" /v Identifier /s
This searches for the registry key named Identifier within Target Id 0
Okay, then try:
This optimized version executes in ~65 ms on my system. That should be good enough.
//ManagementObject sys = new ManagementObject("Win32_OperatingSystem=@");
//string systemDrive = sys["SystemDrive"].ToString();
//Console.WriteLine("System Drive is {0}", systemDrive);
string strQuery = "ASSOCIATORS OF {Win32_LogicalDisk.DeviceID=\""
+ System.IO.Path.GetPathRoot(Environment.SystemDirectory).Replace("\\", "")
+ "\"} WHERE AssocClass = Win32_LogicalDiskToPartition";
RelatedObjectQuery relquery = new RelatedObjectQuery(strQuery);
ManagementObjectSearcher search = new ManagementObjectSearcher(relquery);
UInt32 ndx = 0;
foreach (var diskPartition in search.Get())
{
ndx = (uint)diskPartition["DiskIndex"];
Console.WriteLine("Disk Index of System Drive is {0}, Disk Partition is {1}", ndx, diskPartition["DeviceID"]);
}
SelectQuery diskQuery = new SelectQuery(string.Format("SELECT * FROM Win32_DiskDrive WHERE Index={0}", ndx));
ManagementObjectSearcher diskSearch = new ManagementObjectSearcher(diskQuery);
foreach (var disk in diskSearch.Get())
{
Console.WriteLine("Caption is {0}", disk["Caption"]);
Console.WriteLine("Serial Number is {0}", disk["SerialNumber"]);
Console.WriteLine("Model is {0}", disk["Model"]);
Console.WriteLine("InterfaceType is {0}", disk["InterfaceType"]);
}