private static void assert(SmartDriveInfo drv, bool assertion) { if (!assertion) { throw new SmartReadException("Inconsistent data", drv); } }
/// <summary> /// Retrieves information about physical drives present in the system, omitting any SMART data. Requires /// administrative privileges. See also <see cref="GetDrivesWithSMART"/>.</summary> public static List <SmartDriveInfo> GetDrives() { var drives1 = convert(new ManagementObjectSearcher(@"\\localhost\ROOT\Microsoft\Windows\Storage", "select * from MSFT_PhysicalDisk").Get()); var drives2 = convert(new ManagementObjectSearcher("select * from Win32_DiskDrive").Get()); var drives = new List <SmartDriveInfo>(); foreach (var drive1 in drives1) { var id = drive1.Get("DeviceId", null)?.ToString(); if (id == null || id == "") { throw new SmartReadException($"DeviceId is missing, empty or null", null); } var drive2 = drives2.SingleOrDefault(d2 => d2.Get("Index", null)?.ToString() == id); if (drive2 == null) { throw new SmartReadException($"Could not find matching drive in Win32_DiskDrive: DeviceId={id}", null); } var drive = new SmartDriveInfo(); try { drive.DeviceIndex = drive1["DeviceId"].ToString(); drive.DeviceId_PnP = (string)drive2["PNPDeviceID"]; drive.DeviceId_WinName = (string)drive2["DeviceID"]; drive.DeviceId_UniqueId = (string)drive1["UniqueId"]; drive.UniqueIdType = (UniqueIdType)(ushort)drive1["UniqueIdFormat"]; drive.Model = drive1["Model"].ToString(); drive.SerialNumber = (string)drive1["SerialNumber"]; drive.FirmwareVersion = (string)drive1["FirmwareVersion"]; drive.BusType = (BusType)(ushort)drive1["BusType"]; drive.MediaType = (MediaType)(ushort)drive1["MediaType"]; drive.Size = (ulong)drive1["Size"]; drive.LogicalSectorSize = (ulong)drive1["LogicalSectorSize"]; drive.PhysicalSectorSize = (ulong)drive1["PhysicalSectorSize"]; drive.Location = (string)drive1["PhysicalLocation"]; } catch (Exception e) { throw new SmartReadException("Could not parse WMI data", drive, e); } assert(drive, drive.DeviceId_WinName == (string)drive2["Name"]); assert(drive, drive.Model == (string)drive2["Model"]); assert(drive, drive.Model == (string)drive1["FriendlyName"]); assert(drive, drive.Model == (string)drive2["Caption"]); assert(drive, drive.SerialNumber == ((string)drive2["SerialNumber"]).Trim()); assert(drive, drive.FirmwareVersion == (string)drive2["FirmwareRevision"]); assert(drive, drive.Size >= (ulong)drive2["Size"]); // raw drive can be a little larger assert(drive, drive.LogicalSectorSize == (uint)drive2["BytesPerSector"]); drives.Add(drive); } return(drives); }
private static string getMessage(string message, SmartDriveInfo drv) { if (drv == null) { return(message); } else { return($"{message} [DeviceIndex={drv.DeviceIndex}, Serial={drv?.SerialNumber ?? "?"}]"); } }
internal SmartReadException(string message, SmartDriveInfo drv, Exception inner) : base(getMessage(message, drv), inner) { }