InstalledDevices.cs (4585B)
1 using System.Globalization; 2 using Microsoft.Win32; 3 4 namespace DriverUpdater; 5 6 // A device that has a driver installed. Hardware IDs run from most to least specific, and compatible 7 // IDs are looser still. Windows ranks a driver by how early in that order its INF matches. 8 record InstalledDevice( 9 string DeviceId, 10 string Name, 11 string DeviceClass, 12 string DriverProvider, 13 string DriverVersion, 14 DateTime? DriverDate, 15 string[] HardwareIds, 16 string[] CompatibleIds) 17 { 18 // Reads one field of the device ID. For "PCI\VEN_10DE&DEV_2C05&SUBSYS_89F41043&REV_A1\4&1EBE6A9C" 19 // Field("DEV") is "2C05". 20 public string? Field(string name) => 21 DeviceId.Split('\\').ElementAtOrDefault(1)?.Split('&') 22 .FirstOrDefault(field => field.StartsWith(name + "_", StringComparison.OrdinalIgnoreCase)) 23 ?[(name.Length + 1)..]; 24 25 public bool IsFromVendor(string pciVendorId) => 26 DeviceId.StartsWith($@"PCI\VEN_{pciVendorId}&", StringComparison.OrdinalIgnoreCase); 27 28 // Every ID the device answers to, in the order Windows ranks driver matches. 29 public List<string> AllIds => [.. HardwareIds, .. CompatibleIds]; 30 31 // Reads a value from the device's driver key, where the installed INF writes its settings. The 32 // device's Enum key says which driver key is its own. 33 public string? DriverKeyValue(string name) 34 { 35 using var enumKey = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Enum\{DeviceId}"); 36 if (enumKey?.GetValue("Driver") is not string driverKey) 37 return null; 38 39 using var classKey = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Control\Class\{driverKey}"); 40 return classKey?.GetValue(name) as string; 41 } 42 } 43 44 // Reads the device list from WMI through the WbemScripting COM objects, which keeps the app free of 45 // NuGet packages. Win32_PnPSignedDriver has each device's driver version and date. 46 // Win32_PnPEntity has the full ID lists, which are what drivers match on. 47 static class InstalledDevices 48 { 49 public static List<InstalledDevice> Read() 50 { 51 dynamic locator = Com.Create("WbemScripting.SWbemLocator"); 52 dynamic wmi = locator.ConnectServer(".", @"root\cimv2"); 53 54 var idsByDevice = new Dictionary<string, (string[] Hardware, string[] Compatible)>(StringComparer.OrdinalIgnoreCase); 55 foreach (dynamic entity in wmi.ExecQuery("SELECT DeviceID, HardwareID, CompatibleID FROM Win32_PnPEntity")) 56 { 57 if (Property(entity, "DeviceID") is string deviceId) 58 idsByDevice[deviceId] = (ToStringArray(Property(entity, "HardwareID")), ToStringArray(Property(entity, "CompatibleID"))); 59 } 60 61 var devices = new List<InstalledDevice>(); 62 foreach (dynamic driver in wmi.ExecQuery( 63 "SELECT DeviceID, DeviceName, DeviceClass, DriverProviderName, DriverVersion, DriverDate FROM Win32_PnPSignedDriver")) 64 { 65 // Entries with no device ID or version are driver packages with no device using them. 66 if (Property(driver, "DeviceID") is not string deviceId 67 || Property(driver, "DriverVersion") is not string version) 68 continue; 69 70 var ids = idsByDevice.GetValueOrDefault(deviceId, ([], [])); 71 devices.Add(new InstalledDevice( 72 deviceId, 73 Property(driver, "DeviceName") as string ?? "", 74 Property(driver, "DeviceClass") as string ?? "", 75 Property(driver, "DriverProviderName") as string ?? "", 76 version, 77 ParseWmiDate(Property(driver, "DriverDate") as string), 78 ids.Hardware, 79 ids.Compatible)); 80 } 81 return devices; 82 } 83 84 // Reading properties through Properties_ works for every type. Reading them as members of the 85 // object (entity.HardwareID) fails with E_FAIL on array properties. 86 static object Property(dynamic wmiObject, string name) => wmiObject.Properties_.Item(name).Value; 87 88 // WMI returns DBNull for an empty array property, and an object[] otherwise. 89 static string[] ToStringArray(object value) => 90 value is object[] items ? items.OfType<string>().ToArray() : []; 91 92 // WMI dates look like "20260416000000.******+000". Only the date part matters here. 93 static DateTime? ParseWmiDate(string? value) => 94 value is { Length: >= 8 } 95 && DateTime.TryParseExact(value[..8], "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date) 96 ? date 97 : null; 98 }