driver-updater

Windows app that checks Windows Update and hardware vendors for newer drivers and silently installs the driver.
git clone https://dittus.dev/git/driver-updater.git
Log | Files | Refs | README | Download

DriverInf.cs (4989B)


      1 using System.Globalization;
      2 using System.IO;
      3 using System.Text;
      4 using System.Text.RegularExpressions;
      5 
      6 namespace DriverUpdater;
      7 
      8 // A driver INF inside an unpacked vendor package, and the device ID it matched on.
      9 record DriverInf(string Path, string HardwareId, Version Version, DateTime? Date)
     10 {
     11     // Mirrors how Windows picks between this driver and the installed one. The driver that matches an
     12     // earlier ID in the device's list wins. On a tie the newer date wins, then the higher version.
     13     // MatchingDeviceId in the driver key says which ID the installed driver matched.
     14     public bool IsPreferredOver(InstalledDevice device)
     15     {
     16         var ids = device.AllIds;
     17         int rank = ids.FindIndex(id => id.Equals(HardwareId, StringComparison.OrdinalIgnoreCase));
     18         int installedRank = device.DriverKeyValue("MatchingDeviceId") is string matched
     19             ? ids.FindIndex(id => id.Equals(matched, StringComparison.OrdinalIgnoreCase))
     20             : -1;
     21         if (installedRank >= 0 && rank != installedRank)
     22             return rank < installedRank;
     23 
     24         if (Date is not null && device.DriverDate is not null && Date != device.DriverDate)
     25             return Date > device.DriverDate;
     26 
     27         return Version.TryParse(device.DriverVersion, out var installedVersion) && Version > installedVersion;
     28     }
     29 }
     30 
     31 // The INF files in an unpacked package, read once so many devices can be matched against them.
     32 sealed partial class InfFiles
     33 {
     34     readonly List<(string Path, string Text)> infs;
     35 
     36     InfFiles(List<(string Path, string Text)> infs) => this.infs = infs;
     37 
     38     // Sorting the paths makes ties come out the same way every time. In AMD's chipset package that
     39     // puts the Windows 11 copy of an INF (W11x64) ahead of the Windows 10 copy (WTx64).
     40     public static InfFiles Load(string folder) =>
     41         new(Directory.EnumerateFiles(folder, "*.inf", SearchOption.AllDirectories)
     42             .Order(StringComparer.OrdinalIgnoreCase)
     43             .Select(path => (path, ReadInf(path)))
     44             .ToList());
     45 
     46     // Finds the INF that fits the device best. It tries the device's most specific IDs first, the
     47     // way Windows ranks drivers. Among INFs that list the same ID, the highest DriverVer wins.
     48     public DriverInf? FindFor(InstalledDevice device)
     49     {
     50         foreach (string id in device.AllIds.Where(NamesTheDevice))
     51         {
     52             var best = infs
     53                 .Where(inf => ListsId(inf.Text, id))
     54                 .Select(inf => ParseDriverVer(inf.Path, inf.Text, id))
     55                 .OfType<DriverInf>()
     56                 .MaxBy(inf => inf.Version);
     57             if (best is not null)
     58                 return best;
     59         }
     60         return null;
     61     }
     62 
     63     // Skips IDs that only name a device class, like "PCI\VEN_10DE&CC_030000" or
     64     // "USB\Class_E0&SubClass_01". Those would match drivers meant for other devices.
     65     static bool NamesTheDevice(string id) =>
     66         !id.Contains("CC_", StringComparison.OrdinalIgnoreCase)
     67         && !id.Contains("Class_", StringComparison.OrdinalIgnoreCase);
     68 
     69     // True if the INF lists the ID as a whole, so "PCI\VEN_10DE&DEV_2C05" doesn't match inside
     70     // "PCI\VEN_10DE&DEV_2C05&SUBSYS_89F41043".
     71     static bool ListsId(string text, string id)
     72     {
     73         for (int at = text.IndexOf(id, StringComparison.OrdinalIgnoreCase);
     74              at >= 0;
     75              at = text.IndexOf(id, at + 1, StringComparison.OrdinalIgnoreCase))
     76         {
     77             int end = at + id.Length;
     78             bool startsClean = at == 0 || !IsIdCharacter(text[at - 1]);
     79             bool endsClean = end == text.Length || !IsIdCharacter(text[end]);
     80             if (startsClean && endsClean)
     81                 return true;
     82         }
     83         return false;
     84     }
     85 
     86     static bool IsIdCharacter(char c) => char.IsLetterOrDigit(c) || c is '_' or '&' or '\\';
     87 
     88     // DriverVer looks like "DriverVer = 09/09/2026,1.2.0.133", with the date month first.
     89     static DriverInf? ParseDriverVer(string path, string text, string id)
     90     {
     91         var match = DriverVerLine().Match(text);
     92         if (!match.Success || !Version.TryParse(match.Groups["version"].Value, out var version))
     93             return null;
     94 
     95         DateTime? date = DateTime.TryParseExact(match.Groups["date"].Value, "MM/dd/yyyy",
     96             CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsed) ? parsed : null;
     97         return new DriverInf(path, id, version, date);
     98     }
     99 
    100     // INFs are UTF-16 when they start with a byte order mark, and Windows-1252 or ASCII otherwise.
    101     // Latin1 reads the second kind well enough to find ASCII hardware IDs.
    102     static string ReadInf(string path)
    103     {
    104         using var reader = new StreamReader(path, Encoding.Latin1, detectEncodingFromByteOrderMarks: true);
    105         return reader.ReadToEnd();
    106     }
    107 
    108     [GeneratedRegex(@"^\s*DriverVer\s*=\s*(?<date>[\d/]+)\s*,\s*(?<version>[\d.]+)",
    109         RegexOptions.Multiline | RegexOptions.IgnoreCase)]
    110     private static partial Regex DriverVerLine();
    111 }