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

commit 172fcd6c471f377997e2aab24d54b09c29c18fd7
Author: dittus <dittus@pm.me>
Date:   Tue, 27 Oct 2026 15:17:56 -0400

Initial commit

Diffstat:
A.gitignore | 4++++
AAmd.cs | 213+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AApp.xaml | 6++++++
AApp.xaml.cs | 7+++++++
AAssemblyInfo.cs | 10++++++++++
AAuthenticode.cs | 131+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ACom.cs | 8++++++++
ADriverInf.cs | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ADriverUpdate.cs | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ADriverUpdater.csproj | 22++++++++++++++++++++++
AInstalledDevices.cs | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AIntel.cs | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AMainWindow.xaml | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AMainWindow.xaml.cs | 197+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ANvidia.cs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
APnpDriver.cs | 39+++++++++++++++++++++++++++++++++++++++
AREADME.md | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ARestorePoint.cs | 21+++++++++++++++++++++
AUnpack.cs | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
AVendorPackage.cs | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AWeb.cs | 13+++++++++++++
AWindowsUpdate.cs | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp.manifest | 19+++++++++++++++++++
23 files changed, 1605 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1,4 @@ +bin/ +obj/ +.vs/ +*.user diff --git a/Amd.cs b/Amd.cs @@ -0,0 +1,213 @@ +using System.Globalization; +using System.IO; +using System.Net.Http; +using System.Text.Json; +using System.Xml.Linq; + +namespace DriverUpdater; + +// Checks AMD for the latest Adrenalin graphics driver and the latest chipset drivers. These are the +// feeds AMD's own installer reads. drivers.amd.com redirects any request without an amd.com Referer to +// an error page, for the feeds and the packages alike. +static class Amd +{ + static readonly Uri Referrer = new("https://www.amd.com/"); + const string Signer = "Advanced Micro Devices"; + + const string GraphicsIndexUrl = "https://drivers.amd.com/drivers/installer/json/version.json"; + const string ChipsetInfoUrl = "https://drivers.amd.com/drivers/installer/chipset/VersionInfo.xml"; + static readonly Uri ChipsetPackageUrl = new("https://drivers.amd.com/drivers/installer/chipset/AMD_Chipset_Software.exe"); + + // The graphics feeds, in the order to search them. AMD ships one driver branch for its newest + // GPUs, one for the generation before, and one for older Vega and Polaris parts. + static readonly string[] GraphicsFeeds = + ["Consumer_Whql_Win10_productionASICs", "Consumer_Maintenance_Win10", "Consumer_Legacy_Win10"]; + + public static async Task<List<DriverUpdate>> CheckGraphicsAsync(IReadOnlyList<InstalledDevice> installed) + { + // AMD graphics still use ATI's old PCI vendor ID. + var gpus = installed.Where(d => d.DeviceClass == "DISPLAY" && d.IsFromVendor("1002")).ToList(); + if (gpus.Count == 0) + return []; + + // The index names each feed's URL. The values that aren't feeds are skipped by name. + using var index = JsonDocument.Parse(await GetStringAsync(GraphicsIndexUrl)); + var releases = new List<GraphicsRelease>(); + foreach (string feed in GraphicsFeeds) + { + string feedUrl = OnDriversHost(index.RootElement.GetProperty(feed).GetProperty("url").GetString()!); + releases.AddRange(JsonSerializer.Deserialize<List<GraphicsRelease>>(await GetStringAsync(feedUrl), JsonSerializerOptions.Web)!); + } + + var updates = new List<DriverUpdate>(); + foreach (var gpu in gpus) + { + // Feeds list the GPUs they support as "DEV-REV", like "13C0-C1". + string sku = $"{gpu.Field("DEV")}-{gpu.Field("REV")}"; + var release = releases.FirstOrDefault(r => r.Skus.Contains(sku, StringComparer.OrdinalIgnoreCase)); + if (release is null) + continue; + + // The Windows driver version (32.0.21042.62) has no clean mapping to AMD's numbers, so + // compare AMD's internal build number (25.10.42) instead. The display INF writes it to the + // registry, so it stays right after a driver only install. + // ReleaseVersion looks like "25.10.42-260323a-200157C-Channel". + string? installedBuild = gpu.DriverKeyValue("ReleaseVersion") is string releaseVersion ? BuildNumber(releaseVersion) : null; + string availableBuild = BuildNumber(release.InternalBuildVersion); + bool isNewer = installedBuild is null || Version.Parse(availableBuild) > Version.Parse(installedBuild); + var packageUrl = new Uri(OnDriversHost(release.FullBuild)); + + updates.Add(new DriverUpdate + { + Device = gpu.Name, + Source = "AMD", + InstalledVersion = installedBuild ?? gpu.DriverVersion, + AvailableVersion = $"{release.ExternalBuildVersion} ({availableBuild})", + ReleaseDate = DateTime.ParseExact(release.ReleaseDate, "MM/dd/yyyy", CultureInfo.InvariantCulture), + SizeBytes = (long)(double.Parse(release.FullBuildFileSize, CultureInfo.InvariantCulture) * 1_048_576), + NotesUrl = new Uri(release.ReleaseNotes), + Package = isNewer + ? new VendorPackage(packageUrl, Referrer, Signer, VendorPackage.TempFolderFor(packageUrl), Unpack.WithTarAsync) + : null, + TargetDevice = gpu, + Status = isNewer ? "Update available" : "Up to date", + }); + } + return updates; + } + + // Chipset drivers are many small drivers in one package, so each device gets its own row. Only + // devices that already run an AMD driver are compared. Devices on Microsoft's drivers are left alone. + public static async Task<List<DriverUpdate>> CheckChipsetAsync(IReadOnlyList<InstalledDevice> installed) + { + // VEN_1022 is AMD's PCI vendor ID for CPUs and chipsets. + if (!installed.Any(d => d.IsFromVendor("1022"))) + return []; + + var info = XDocument.Parse(await GetStringAsync(ChipsetInfoUrl)).Root!; + string packageVersion = info.Element("Version")!.Value; + var notes = new Uri(info.Element("ReleaseNotes")!.Value); + + if (Unpack.SevenZipPath() is null) + { + return [new DriverUpdate + { + Device = "AMD chipset drivers", + Source = "AMD chipset", + AvailableVersion = packageVersion, + NotesUrl = notes, + Status = "Install 7-Zip to check these", + }]; + } + + // The package is kept between runs, one folder per AMD release, so a scan only downloads it + // when AMD publishes a new one. + string cache = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DriverUpdater"); + string folder = Path.Combine(cache, $"amd-chipset-{packageVersion}"); + var package = new VendorPackage(ChipsetPackageUrl, Referrer, Signer, folder, UnpackChipsetAsync) + { + KeepAfterInstall = true, + }; + var infs = InfFiles.Load(await package.UnpackAsync(_ => { })); + DeleteOlderChipsetPackages(cache, folder); + + var updates = new List<DriverUpdate>(); + var infsSeen = new HashSet<(string, string)>(); + foreach (var device in installed.Where(d => IsAmdDriver(d.DriverProvider))) + { + var inf = infs.FindFor(device); + if (inf is null || !inf.IsPreferredOver(device)) + continue; + + // Installing by hardware ID updates every device with that ID, so list each pair once. + if (!infsSeen.Add((inf.HardwareId, inf.Path))) + continue; + + updates.Add(new DriverUpdate + { + Device = device.Name, + Source = "AMD chipset", + InstalledVersion = device.DriverVersion, + AvailableVersion = inf.Version.ToString(), + ReleaseDate = inf.Date, + NotesUrl = notes, + Package = package, + TargetDevice = device, + Status = "Update available", + }); + } + + if (updates.Count == 0) + { + updates.Add(new DriverUpdate + { + Device = "AMD chipset drivers", + Source = "AMD chipset", + AvailableVersion = packageVersion, + NotesUrl = notes, + Status = "Up to date", + }); + } + return updates; + } + + static bool IsAmdDriver(string provider) => + provider.StartsWith("Advanced Micro Devices", StringComparison.OrdinalIgnoreCase) + || provider.Equals("AMD", StringComparison.OrdinalIgnoreCase); + + // The chipset package is an NSIS installer holding an InstallShield setup that holds the drivers. + // 7-Zip opens the NSIS layer. The InstallShield layer unpacks itself through an MSI administrative + // install, which copies the files out and installs nothing. AMD's own installer unpacks it the + // same way. + static async Task UnpackChipsetAsync(string package, string folder) + { + string sevenZip = Unpack.SevenZipPath() ?? throw new InvalidOperationException("7-Zip isn't installed"); + Directory.CreateDirectory(folder); + await Unpack.RunAsync(sevenZip, $"e -y \"-o{folder}\" \"{package}\" AMD_Chipset_Drivers.exe"); + + string setup = Path.Combine(folder, "AMD_Chipset_Drivers.exe"); + if (!Authenticode.IsSignedBy(setup, Signer)) + throw new InvalidOperationException($"AMD_Chipset_Drivers.exe isn't signed by {Signer}"); + + // Comes out as: /s /a /v"/qn GONOGO=PUBLICGO TARGETDIR=\"C:\path\"" + // GONOGO=PUBLICGO is the property AMD's own installer passes. + await Unpack.RunAsync(setup, $"/s /a /v\"/qn GONOGO=PUBLICGO TARGETDIR=\\\"{folder}\\\"\""); + File.Delete(setup); + } + + static void DeleteOlderChipsetPackages(string cache, string current) + { + foreach (string old in Directory.EnumerateDirectories(cache, "amd-chipset-*")) + { + if (!old.Equals(current, StringComparison.OrdinalIgnoreCase)) + Directory.Delete(old, recursive: true); + } + } + + // "25.10.45.16-261009a-205305C-AMD-Software-Adrenalin-Edition" becomes "25.10.45". The installed + // build has only three fields, so both sides are cut to three. + static string BuildNumber(string release) => + string.Join('.', release.Split('-')[0].Split('.').Take(3)); + + // The feeds name www2.ati.com, which only redirects to drivers.amd.com. + static string OnDriversHost(string url) => new UriBuilder(url) { Host = "drivers.amd.com" }.Uri.ToString(); + + static async Task<string> GetStringAsync(string url) + { + using var request = new HttpRequestMessage(HttpMethod.Get, url) { Headers = { Referrer = Referrer } }; + using var response = await Web.Client.SendAsync(request); + response.EnsureSuccessStatusCode(); + return await response.Content.ReadAsStringAsync(); + } + + // The parts of a graphics feed entry the app reads. The feed's keys are all lowercase, which + // JsonSerializerOptions.Web matches without regard to case. + record GraphicsRelease( + string ExternalBuildVersion, + string InternalBuildVersion, + string ReleaseDate, + string FullBuild, + string FullBuildFileSize, + string ReleaseNotes, + List<string> Skus); +} diff --git a/App.xaml b/App.xaml @@ -0,0 +1,6 @@ +<Application x:Class="DriverUpdater.App" + xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" + StartupUri="MainWindow.xaml" + ThemeMode="System"> +</Application> diff --git a/App.xaml.cs b/App.xaml.cs @@ -0,0 +1,7 @@ +using System.Windows; + +namespace DriverUpdater; + +public partial class App : Application +{ +} diff --git a/AssemblyInfo.cs b/AssemblyInfo.cs @@ -0,0 +1,10 @@ +using System.Windows; + +[assembly:ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] diff --git a/Authenticode.cs b/Authenticode.cs @@ -0,0 +1,131 @@ +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; +using System.Security.Cryptography.X509Certificates; + +namespace DriverUpdater; + +// Checks a downloaded installer's Authenticode signature before the app runs it. WinVerifyTrust +// checks that the signature matches the file and chains to a trusted root, with revocation checks. +// The name then comes from the certificate of the signer WinVerifyTrust just checked. +static class Authenticode +{ + public static bool IsSignedBy(string path, string company) => + VerifiedSignerName(path)?.Equals(company, StringComparison.OrdinalIgnoreCase) == true; + + // Returns the signer's name if the signature is valid, or null if it isn't. + static string? VerifiedSignerName(string path) + { + var fileInfo = new WinTrustFileInfo + { + StructSize = Marshal.SizeOf<WinTrustFileInfo>(), + FilePath = path, + }; + IntPtr fileInfoPointer = Marshal.AllocHGlobal(fileInfo.StructSize); + try + { + Marshal.StructureToPtr(fileInfo, fileInfoPointer, fDeleteOld: false); + var data = new WinTrustData + { + StructSize = Marshal.SizeOf<WinTrustData>(), + UIChoice = WtdUiNone, + RevocationChecks = WtdRevokeWholeChain, + UnionChoice = WtdChoiceFile, + FileInfo = fileInfoPointer, + StateAction = WtdStateActionVerify, + }; + var action = GenericVerifyV2; + int result = WinVerifyTrust(IntPtr.Zero, ref action, ref data); + string? signerName = result == 0 ? SignerName(data.StateData) : null; + + // Free the state WinVerifyTrust kept from the verify call. + data.StateAction = WtdStateActionClose; + WinVerifyTrust(IntPtr.Zero, ref action, ref data); + + return signerName; + } + finally + { + Marshal.DestroyStructure<WinTrustFileInfo>(fileInfoPointer); + Marshal.FreeHGlobal(fileInfoPointer); + } + } + + // Walks from WinVerifyTrust's state to the signer, then to the first certificate in the signer's + // chain, which is the signer's own. + static string SignerName(IntPtr stateData) + { + IntPtr providerData = WTHelperProvDataFromStateData(stateData); + IntPtr signerPointer = WTHelperGetProvSignerFromChain(providerData, 0, false, 0); + var signer = Marshal.PtrToStructure<CryptProviderSigner>(signerPointer); + var signerCertificate = Marshal.PtrToStructure<CryptProviderCert>(signer.CertChain); + + using var certificate = new X509Certificate2(signerCertificate.CertContext); + return certificate.GetNameInfo(X509NameType.SimpleName, forIssuer: false); + } + + // WINTRUST_ACTION_GENERIC_VERIFY_V2: the standard Authenticode policy. + static readonly Guid GenericVerifyV2 = new("00AAC56B-CD44-11d0-8CC2-00C04FC295EE"); + + const int WtdUiNone = 2; + const int WtdRevokeWholeChain = 1; + const int WtdChoiceFile = 1; + const int WtdStateActionVerify = 1; + const int WtdStateActionClose = 2; + + [DllImport("wintrust.dll", ExactSpelling = true)] + static extern int WinVerifyTrust(IntPtr window, ref Guid action, ref WinTrustData data); + + [DllImport("wintrust.dll", ExactSpelling = true)] + static extern IntPtr WTHelperProvDataFromStateData(IntPtr stateData); + + [DllImport("wintrust.dll", ExactSpelling = true)] + static extern IntPtr WTHelperGetProvSignerFromChain( + IntPtr providerData, int signerIndex, bool counterSigner, int counterSignerIndex); + + // WINTRUST_FILE_INFO + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + struct WinTrustFileInfo + { + public int StructSize; + public string FilePath; + public IntPtr FileHandle; + public IntPtr KnownSubject; + } + + // WINTRUST_DATA + [StructLayout(LayoutKind.Sequential)] + struct WinTrustData + { + public int StructSize; + public IntPtr PolicyCallbackData; + public IntPtr SipClientData; + public int UIChoice; + public int RevocationChecks; + public int UnionChoice; + public IntPtr FileInfo; + public int StateAction; + public IntPtr StateData; + public IntPtr UrlReference; + public int ProvFlags; + public int UIContext; + public IntPtr SignatureSettings; + } + + // The leading fields of CRYPT_PROVIDER_SGNR. The rest aren't needed. + [StructLayout(LayoutKind.Sequential)] + struct CryptProviderSigner + { + public int StructSize; + public FILETIME VerifyAsOf; + public int CertChainCount; + public IntPtr CertChain; + } + + // The leading fields of CRYPT_PROVIDER_CERT. + [StructLayout(LayoutKind.Sequential)] + struct CryptProviderCert + { + public int StructSize; + public IntPtr CertContext; + } +} diff --git a/Com.cs b/Com.cs @@ -0,0 +1,8 @@ +namespace DriverUpdater; + +static class Com +{ + // Creates a COM object by its ProgID, to be called through dynamic. + public static dynamic Create(string progId) => + Activator.CreateInstance(Type.GetTypeFromProgID(progId, throwOnError: true)!)!; +} diff --git a/DriverInf.cs b/DriverInf.cs @@ -0,0 +1,111 @@ +using System.Globalization; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; + +namespace DriverUpdater; + +// A driver INF inside an unpacked vendor package, and the device ID it matched on. +record DriverInf(string Path, string HardwareId, Version Version, DateTime? Date) +{ + // Mirrors how Windows picks between this driver and the installed one. The driver that matches an + // earlier ID in the device's list wins. On a tie the newer date wins, then the higher version. + // MatchingDeviceId in the driver key says which ID the installed driver matched. + public bool IsPreferredOver(InstalledDevice device) + { + var ids = device.AllIds; + int rank = ids.FindIndex(id => id.Equals(HardwareId, StringComparison.OrdinalIgnoreCase)); + int installedRank = device.DriverKeyValue("MatchingDeviceId") is string matched + ? ids.FindIndex(id => id.Equals(matched, StringComparison.OrdinalIgnoreCase)) + : -1; + if (installedRank >= 0 && rank != installedRank) + return rank < installedRank; + + if (Date is not null && device.DriverDate is not null && Date != device.DriverDate) + return Date > device.DriverDate; + + return Version.TryParse(device.DriverVersion, out var installedVersion) && Version > installedVersion; + } +} + +// The INF files in an unpacked package, read once so many devices can be matched against them. +sealed partial class InfFiles +{ + readonly List<(string Path, string Text)> infs; + + InfFiles(List<(string Path, string Text)> infs) => this.infs = infs; + + // Sorting the paths makes ties come out the same way every time. In AMD's chipset package that + // puts the Windows 11 copy of an INF (W11x64) ahead of the Windows 10 copy (WTx64). + public static InfFiles Load(string folder) => + new(Directory.EnumerateFiles(folder, "*.inf", SearchOption.AllDirectories) + .Order(StringComparer.OrdinalIgnoreCase) + .Select(path => (path, ReadInf(path))) + .ToList()); + + // Finds the INF that fits the device best. It tries the device's most specific IDs first, the + // way Windows ranks drivers. Among INFs that list the same ID, the highest DriverVer wins. + public DriverInf? FindFor(InstalledDevice device) + { + foreach (string id in device.AllIds.Where(NamesTheDevice)) + { + var best = infs + .Where(inf => ListsId(inf.Text, id)) + .Select(inf => ParseDriverVer(inf.Path, inf.Text, id)) + .OfType<DriverInf>() + .MaxBy(inf => inf.Version); + if (best is not null) + return best; + } + return null; + } + + // Skips IDs that only name a device class, like "PCI\VEN_10DE&CC_030000" or + // "USB\Class_E0&SubClass_01". Those would match drivers meant for other devices. + static bool NamesTheDevice(string id) => + !id.Contains("CC_", StringComparison.OrdinalIgnoreCase) + && !id.Contains("Class_", StringComparison.OrdinalIgnoreCase); + + // True if the INF lists the ID as a whole, so "PCI\VEN_10DE&DEV_2C05" doesn't match inside + // "PCI\VEN_10DE&DEV_2C05&SUBSYS_89F41043". + static bool ListsId(string text, string id) + { + for (int at = text.IndexOf(id, StringComparison.OrdinalIgnoreCase); + at >= 0; + at = text.IndexOf(id, at + 1, StringComparison.OrdinalIgnoreCase)) + { + int end = at + id.Length; + bool startsClean = at == 0 || !IsIdCharacter(text[at - 1]); + bool endsClean = end == text.Length || !IsIdCharacter(text[end]); + if (startsClean && endsClean) + return true; + } + return false; + } + + static bool IsIdCharacter(char c) => char.IsLetterOrDigit(c) || c is '_' or '&' or '\\'; + + // DriverVer looks like "DriverVer = 09/09/2026,1.2.0.133", with the date month first. + static DriverInf? ParseDriverVer(string path, string text, string id) + { + var match = DriverVerLine().Match(text); + if (!match.Success || !Version.TryParse(match.Groups["version"].Value, out var version)) + return null; + + DateTime? date = DateTime.TryParseExact(match.Groups["date"].Value, "MM/dd/yyyy", + CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsed) ? parsed : null; + return new DriverInf(path, id, version, date); + } + + // INFs are UTF-16 when they start with a byte order mark, and Windows-1252 or ASCII otherwise. + // Latin1 reads the second kind well enough to find ASCII hardware IDs. + static string ReadInf(string path) + { + using var reader = new StreamReader(path, Encoding.Latin1, detectEncodingFromByteOrderMarks: true); + return reader.ReadToEnd(); + } + + [GeneratedRegex(@"^\s*DriverVer\s*=\s*(?<date>[\d/]+)\s*,\s*(?<version>[\d.]+)", + RegexOptions.Multiline | RegexOptions.IgnoreCase)] + private static partial Regex DriverVerLine(); +} diff --git a/DriverUpdate.cs b/DriverUpdate.cs @@ -0,0 +1,56 @@ +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace DriverUpdater; + +// One row in the list. Usually a device with a newer driver available. Vendor checks also add a row +// when the device is already up to date or the check failed, so you can see the check ran. +sealed class DriverUpdate : INotifyPropertyChanged +{ + public required string Device { get; init; } + public required string Source { get; init; } + public string InstalledVersion { get; init; } = ""; + public string AvailableVersion { get; init; } = ""; + public DateTime? ReleaseDate { get; init; } + public long? SizeBytes { get; init; } + public Uri? NotesUrl { get; init; } + + // How to install it. A Windows Update row carries the update's COM object. A vendor row carries + // the package that holds the driver and the device to install it on. + public object? WindowsUpdateItem { get; init; } + public VendorPackage? Package { get; init; } + public InstalledDevice? TargetDevice { get; init; } + + public bool CanInstall => WindowsUpdateItem is not null || Package is not null; + + public string SizeText => SizeBytes is long bytes ? $"{bytes / 1_048_576.0:0.#} MB" : ""; + + public bool IsSelected + { + get; + set + { + if (field == value) + return; + field = value; + Changed(); + } + } + + public string Status + { + get; + set + { + if (field == value) + return; + field = value; + Changed(); + } + } = ""; + + public event PropertyChangedEventHandler? PropertyChanged; + + void Changed([CallerMemberName] string? property = null) => + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property)); +} diff --git a/DriverUpdater.csproj b/DriverUpdater.csproj @@ -0,0 +1,22 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <OutputType>WinExe</OutputType> + <TargetFramework>net10.0-windows</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <UseWPF>true</UseWPF> + <ApplicationManifest>app.manifest</ApplicationManifest> + <Version>0.1.0</Version> + </PropertyGroup> + + <!-- dotnet publish -c Release makes one exe that runs without .NET installed. --> + <PropertyGroup Condition="'$(Configuration)' == 'Release'"> + <RuntimeIdentifier>win-x64</RuntimeIdentifier> + <SelfContained>true</SelfContained> + <PublishSingleFile>true</PublishSingleFile> + <IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract> + <EnableCompressionInSingleFile>true</EnableCompressionInSingleFile> + </PropertyGroup> + +</Project> diff --git a/InstalledDevices.cs b/InstalledDevices.cs @@ -0,0 +1,98 @@ +using System.Globalization; +using Microsoft.Win32; + +namespace DriverUpdater; + +// A device that has a driver installed. Hardware IDs run from most to least specific, and compatible +// IDs are looser still. Windows ranks a driver by how early in that order its INF matches. +record InstalledDevice( + string DeviceId, + string Name, + string DeviceClass, + string DriverProvider, + string DriverVersion, + DateTime? DriverDate, + string[] HardwareIds, + string[] CompatibleIds) +{ + // Reads one field of the device ID. For "PCI\VEN_10DE&DEV_2C05&SUBSYS_89F41043&REV_A1\4&1EBE6A9C" + // Field("DEV") is "2C05". + public string? Field(string name) => + DeviceId.Split('\\').ElementAtOrDefault(1)?.Split('&') + .FirstOrDefault(field => field.StartsWith(name + "_", StringComparison.OrdinalIgnoreCase)) + ?[(name.Length + 1)..]; + + public bool IsFromVendor(string pciVendorId) => + DeviceId.StartsWith($@"PCI\VEN_{pciVendorId}&", StringComparison.OrdinalIgnoreCase); + + // Every ID the device answers to, in the order Windows ranks driver matches. + public List<string> AllIds => [.. HardwareIds, .. CompatibleIds]; + + // Reads a value from the device's driver key, where the installed INF writes its settings. The + // device's Enum key says which driver key is its own. + public string? DriverKeyValue(string name) + { + using var enumKey = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Enum\{DeviceId}"); + if (enumKey?.GetValue("Driver") is not string driverKey) + return null; + + using var classKey = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Control\Class\{driverKey}"); + return classKey?.GetValue(name) as string; + } +} + +// Reads the device list from WMI through the WbemScripting COM objects, which keeps the app free of +// NuGet packages. Win32_PnPSignedDriver has each device's driver version and date. +// Win32_PnPEntity has the full ID lists, which are what drivers match on. +static class InstalledDevices +{ + public static List<InstalledDevice> Read() + { + dynamic locator = Com.Create("WbemScripting.SWbemLocator"); + dynamic wmi = locator.ConnectServer(".", @"root\cimv2"); + + var idsByDevice = new Dictionary<string, (string[] Hardware, string[] Compatible)>(StringComparer.OrdinalIgnoreCase); + foreach (dynamic entity in wmi.ExecQuery("SELECT DeviceID, HardwareID, CompatibleID FROM Win32_PnPEntity")) + { + if (Property(entity, "DeviceID") is string deviceId) + idsByDevice[deviceId] = (ToStringArray(Property(entity, "HardwareID")), ToStringArray(Property(entity, "CompatibleID"))); + } + + var devices = new List<InstalledDevice>(); + foreach (dynamic driver in wmi.ExecQuery( + "SELECT DeviceID, DeviceName, DeviceClass, DriverProviderName, DriverVersion, DriverDate FROM Win32_PnPSignedDriver")) + { + // Entries with no device ID or version are driver packages with no device using them. + if (Property(driver, "DeviceID") is not string deviceId + || Property(driver, "DriverVersion") is not string version) + continue; + + var ids = idsByDevice.GetValueOrDefault(deviceId, ([], [])); + devices.Add(new InstalledDevice( + deviceId, + Property(driver, "DeviceName") as string ?? "", + Property(driver, "DeviceClass") as string ?? "", + Property(driver, "DriverProviderName") as string ?? "", + version, + ParseWmiDate(Property(driver, "DriverDate") as string), + ids.Hardware, + ids.Compatible)); + } + return devices; + } + + // Reading properties through Properties_ works for every type. Reading them as members of the + // object (entity.HardwareID) fails with E_FAIL on array properties. + static object Property(dynamic wmiObject, string name) => wmiObject.Properties_.Item(name).Value; + + // WMI returns DBNull for an empty array property, and an object[] otherwise. + static string[] ToStringArray(object value) => + value is object[] items ? items.OfType<string>().ToArray() : []; + + // WMI dates look like "20260416000000.******+000". Only the date part matters here. + static DateTime? ParseWmiDate(string? value) => + value is { Length: >= 8 } + && DateTime.TryParseExact(value[..8], "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date) + ? date + : null; +} diff --git a/Intel.cs b/Intel.cs @@ -0,0 +1,110 @@ +using System.IO; +using System.IO.Compression; +using System.IO.Enumeration; +using System.Text.Json; + +namespace DriverUpdater; + +// Checks Intel's driver catalog. It's the feed Intel Driver & Support Assistant reads: a zip holding a +// JSON list of driver packages, each with the hardware ID patterns it supports. It covers graphics, +// wireless, and Ethernet drivers. +// +// Intel rows are check only. Intel packs graphics, Wi-Fi, and Bluetooth drivers in three different +// installer formats, and installing the driver alone needs unpacking code for each. That waits for +// a machine with Intel hardware to test it on. +static class Intel +{ + const string CatalogUrl = "https://dsadata.intel.com/data/en"; + + public static async Task<List<DriverUpdate>> CheckAsync(IReadOnlyList<InstalledDevice> installed) + { + // Skip the download on machines with no Intel PCI devices (VEN_8086) or Intel Bluetooth (VID_8087). + bool hasIntelHardware = installed.Any(d => + d.IsFromVendor("8086") || d.DeviceId.StartsWith(@"USB\VID_8087&", StringComparison.OrdinalIgnoreCase)); + if (!hasIntelHardware) + return []; + + var packages = await DownloadCatalogAsync(); + + // Packages list the Windows releases they support, like "windows-11-25h2-64". Matching on + // the major version means a new Windows release works before Intel adds it to the list. + string windows = Environment.OSVersion.Version.Build >= 22000 ? "windows-11-" : "windows-10-"; + + var updates = new List<DriverUpdate>(); + var packagesSeen = new HashSet<int>(); + foreach (var device in installed) + { + var match = NewestPackageFor(device, packages, windows); + + // One installer covers every device in a package, so list each package once. + if (match is not var (package, file, version) || !packagesSeen.Add(package.Id)) + continue; + + bool isNewer = !Version.TryParse(device.DriverVersion, out var installedVersion) + || version > installedVersion; + updates.Add(new DriverUpdate + { + Device = device.Name, + Source = "Intel", + InstalledVersion = device.DriverVersion, + AvailableVersion = version.ToString(), + ReleaseDate = package.DisplayReleaseDate, + SizeBytes = file.Size, + NotesUrl = new Uri(package.Url), + Status = isNewer ? "Newer on Intel's site" : "Up to date", + }); + } + return updates; + } + + static async Task<List<Package>> DownloadCatalogAsync() + { + byte[] zipBytes = await Web.Client.GetByteArrayAsync(CatalogUrl); + using var zip = new ZipArchive(new MemoryStream(zipBytes)); + await using var json = zip.GetEntry("software-configurations.json")!.Open(); + return await JsonSerializer.DeserializeAsync<List<Package>>(json) ?? []; + } + + // The newest package with a component whose patterns match this device. Some patterns appear in + // more than one package, and "Historical" packages hold old releases kept for reference. + static (Package, PackageFile, Version)? NewestPackageFor( + InstalledDevice device, List<Package> packages, string windows) + { + // "PCI\VEN_8086&DEV_51F0&SUBSYS_00948086&REV_01\3&11583659&0&A3" has the bus, the hardware + // fields, and the instance path. Only the hardware fields take part in matching. + string[] deviceIdParts = device.DeviceId.Split('\\'); + if (deviceIdParts.Length < 3) + return null; + string[] deviceFields = deviceIdParts[1].Split('&'); + + var candidates = + from package in packages + where !package.Name.StartsWith("Historical") + let file = package.Files.FirstOrDefault(f => + f.OperatingSystems.Any(os => os.StartsWith(windows) && os.EndsWith("-64"))) + where file is not null + from component in package.Components + where component.DetectionType == "Default" + where Version.TryParse(component.Version, out _) + where component.DetectionValues?.Any(pattern => Matches(deviceFields, pattern)) == true + select (package, file, Version.Parse(component.Version!)); + + return candidates.Any() ? candidates.MaxBy(candidate => candidate.Item3) : null; + } + + // Patterns look like "VEN_8086&DEV_51F0&SUBSYS_*8086". They're compared field by field, so a + // wildcard can't spill from one field into the next. A pattern can have fewer fields than the ID. + static bool Matches(string[] deviceFields, string pattern) + { + string[] patternFields = pattern.Split('&'); + return patternFields.Length <= deviceFields.Length + && patternFields.Zip(deviceFields).All(pair => + FileSystemName.MatchesSimpleExpression(pair.First, pair.Second, ignoreCase: true)); + } + + // The parts of the catalog the app reads. + record Package(int Id, string Name, DateTime? DisplayReleaseDate, string Url, + List<PackageFile> Files, List<Component> Components); + record PackageFile(string Url, long Size, List<string> OperatingSystems); + record Component(string? Version, string DetectionType, List<string>? DetectionValues); +} diff --git a/MainWindow.xaml b/MainWindow.xaml @@ -0,0 +1,87 @@ +<Window x:Class="DriverUpdater.MainWindow" + xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" + Title="Driver Updater" Width="1100" Height="600" MinWidth="800" MinHeight="400" + WindowStartupLocation="CenterScreen" + Style="{StaticResource {x:Type Window}}"> + <Window.Resources> + <!-- Cell text, centered in the row to line up with the checkbox and the link. --> + <Style x:Key="CellText" TargetType="TextBlock" BasedOn="{x:Static DataGridTextColumn.DefaultElementStyle}"> + <Setter Property="VerticalAlignment" Value="Center" /> + </Style> + <!-- Failure messages can run long, so the full status also shows on hover. --> + <Style x:Key="StatusText" TargetType="TextBlock" BasedOn="{StaticResource CellText}"> + <Setter Property="TextTrimming" Value="CharacterEllipsis" /> + <Setter Property="ToolTip" Value="{Binding Status}" /> + </Style> + </Window.Resources> + + <Grid Margin="16"> + <Grid.RowDefinitions> + <RowDefinition Height="Auto" /> + <RowDefinition Height="*" /> + <RowDefinition Height="Auto" /> + </Grid.RowDefinitions> + + <StackPanel Orientation="Horizontal"> + <Button x:Name="ScanButton" Content="Scan" Click="Scan_Click" MinWidth="90" /> + <Button x:Name="InstallButton" Content="Install selected" Click="Install_Click" + Style="{StaticResource AccentButtonStyle}" Margin="8,0,0,0" IsEnabled="False" /> + <CheckBox x:Name="RestorePointBox" Content="Create a restore point first" IsChecked="True" + Margin="16,0,0,0" VerticalAlignment="Center" /> + </StackPanel> + + <DataGrid x:Name="UpdatesGrid" Grid.Row="1" Margin="0,12" + AutoGenerateColumns="False" CanUserAddRows="False" HeadersVisibility="Column" + SelectionMode="Single" GridLinesVisibility="None"> + <DataGrid.Columns> + <DataGridTemplateColumn Width="Auto"> + <DataGridTemplateColumn.CellTemplate> + <DataTemplate> + <CheckBox IsChecked="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}" + IsEnabled="{Binding CanInstall}" HorizontalAlignment="Center" /> + </DataTemplate> + </DataGridTemplateColumn.CellTemplate> + </DataGridTemplateColumn> + <DataGridTextColumn Header="Device" Binding="{Binding Device}" Width="1.4*" IsReadOnly="True" + ElementStyle="{StaticResource CellText}" /> + <DataGridTextColumn Header="Source" Binding="{Binding Source}" Width="Auto" IsReadOnly="True" + ElementStyle="{StaticResource CellText}" /> + <DataGridTextColumn Header="Installed" Binding="{Binding InstalledVersion}" Width="Auto" IsReadOnly="True" + ElementStyle="{StaticResource CellText}" /> + <DataGridTextColumn Header="Available" Binding="{Binding AvailableVersion}" Width="Auto" IsReadOnly="True" + ElementStyle="{StaticResource CellText}" /> + <DataGridTextColumn Header="Released" Binding="{Binding ReleaseDate, StringFormat=yyyy-MM-dd}" Width="Auto" IsReadOnly="True" + ElementStyle="{StaticResource CellText}" /> + <DataGridTextColumn Header="Size" Binding="{Binding SizeText}" Width="Auto" IsReadOnly="True" + ElementStyle="{StaticResource CellText}" /> + <DataGridTextColumn Header="Status" Binding="{Binding Status}" Width="*" MinWidth="130" IsReadOnly="True" + ElementStyle="{StaticResource StatusText}" /> + <DataGridTemplateColumn Header="Notes" Width="Auto"> + <DataGridTemplateColumn.CellTemplate> + <DataTemplate> + <TextBlock VerticalAlignment="Center"> + <TextBlock.Style> + <Style TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}"> + <Style.Triggers> + <DataTrigger Binding="{Binding NotesUrl}" Value="{x:Null}"> + <Setter Property="Visibility" Value="Collapsed" /> + </DataTrigger> + </Style.Triggers> + </Style> + </TextBlock.Style> + <Hyperlink NavigateUri="{Binding NotesUrl}" RequestNavigate="Link_RequestNavigate">Details</Hyperlink> + </TextBlock> + </DataTemplate> + </DataGridTemplateColumn.CellTemplate> + </DataGridTemplateColumn> + </DataGrid.Columns> + </DataGrid> + + <StackPanel Grid.Row="2" Orientation="Horizontal"> + <ProgressBar x:Name="BusyBar" IsIndeterminate="True" Width="120" Margin="0,0,12,0" + VerticalAlignment="Center" Visibility="Collapsed" /> + <TextBlock x:Name="StatusText" VerticalAlignment="Center" /> + </StackPanel> + </Grid> +</Window> diff --git a/MainWindow.xaml.cs b/MainWindow.xaml.cs @@ -0,0 +1,197 @@ +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows; +using System.Windows.Navigation; + +namespace DriverUpdater; + +public partial class MainWindow : Window +{ + // Each check returns rows for the devices it covers, or none when that hardware isn't present. + static readonly (string Name, Func<IReadOnlyList<InstalledDevice>, Task<List<DriverUpdate>>> Run)[] Checks = + [ + ("Windows Update", installed => Task.Run(() => WindowsUpdate.Search(installed))), + ("NVIDIA", Nvidia.CheckAsync), + ("AMD graphics", Amd.CheckGraphicsAsync), + ("AMD chipset", Amd.CheckChipsetAsync), + ("Intel", Intel.CheckAsync), + ]; + + readonly ObservableCollection<DriverUpdate> rows = []; + bool busy; + + public MainWindow() + { + InitializeComponent(); + UpdatesGrid.ItemsSource = rows; + Loaded += async (_, _) => await ScanAsync(); + } + + async void Scan_Click(object sender, RoutedEventArgs e) => await ScanAsync(); + + async void Install_Click(object sender, RoutedEventArgs e) + { + var chosen = rows.Where(row => row.IsSelected && row.CanInstall).ToList(); + SetBusy(true); + + if (RestorePointBox.IsChecked == true && !await CreateRestorePointAsync()) + { + StatusText.Text = "Nothing installed"; + SetBusy(false); + return; + } + + bool restartNeeded = false; + foreach (var update in chosen) + { + StatusText.Text = $"Updating {update.Device}"; + try + { + restartNeeded |= await InstallAsync(update); + update.IsSelected = false; + } + catch (Exception ex) + { + update.Status = $"Failed: {ex.Message}"; + } + } + + StatusText.Text = "Cleaning up"; + await DeleteTemporaryPackagesAsync(chosen); + StatusText.Text = restartNeeded ? "Done. Restart Windows to finish." : "Done"; + SetBusy(false); + } + + async Task ScanAsync() + { + SetBusy(true); + rows.Clear(); + StatusText.Text = "Reading installed drivers"; + List<InstalledDevice> installed; + try + { + installed = await Task.Run(InstalledDevices.Read); + } + catch (Exception ex) + { + // Every check needs the device list, so there's nothing to do without it. + StatusText.Text = $"Couldn't read installed drivers from WMI: {ex.Message}"; + SetBusy(false); + return; + } + + StatusText.Text = "Checking Windows Update, NVIDIA, AMD, and Intel"; + var results = await Task.WhenAll(Checks.Select(check => RunCheckAsync(check.Name, check.Run, installed))); + foreach (var row in results.SelectMany(rowsFromOneCheck => rowsFromOneCheck)) + { + row.PropertyChanged += Row_PropertyChanged; + rows.Add(row); + } + + int available = rows.Count(row => row.CanInstall); + StatusText.Text = available == 0 ? "No updates found" : $"{available} updates available"; + SetBusy(false); + } + + // A failed check becomes a row of its own, so one vendor being down doesn't hide the others. + static async Task<List<DriverUpdate>> RunCheckAsync( + string name, + Func<IReadOnlyList<InstalledDevice>, Task<List<DriverUpdate>>> run, + IReadOnlyList<InstalledDevice> installed) + { + try + { + return await run(installed); + } + catch (Exception ex) + { + return [new DriverUpdate { Device = $"{name} check", Source = name, Status = $"Failed: {ex.Message}" }]; + } + } + + // Returns true if Windows needs a restart to finish. + static async Task<bool> InstallAsync(DriverUpdate update) + { + if (update.WindowsUpdateItem is { } item) + { + update.Status = "Downloading"; + await Task.Run(() => WindowsUpdate.Download(item)); + update.Status = "Installing"; + bool restartNeeded = await Task.Run(() => WindowsUpdate.Install(item)); + update.Status = restartNeeded ? "Installed. Restart needed" : "Installed"; + return restartNeeded; + } + + // A vendor driver. Unpack the vendor's package and install only the INF for this device. + string folder = await update.Package!.UnpackAsync(status => update.Status = status); + update.Status = "Finding the driver"; + var inf = await Task.Run(() => InfFiles.Load(folder).FindFor(update.TargetDevice!)) + ?? throw new InvalidOperationException("Nothing in the package matches this device"); + + update.Status = "Installing"; + var result = await Task.Run(() => PnpDriver.Install(inf)); + update.Status = result switch + { + DriverInstallResult.Installed => "Installed", + DriverInstallResult.RestartNeeded => "Installed. Restart needed", + _ => "Windows kept the current driver", + }; + return result == DriverInstallResult.RestartNeeded; + } + + // Graphics packages unpack to several GB, so they go once every row that needs them is done. + static Task DeleteTemporaryPackagesAsync(IEnumerable<DriverUpdate> installed) => + Task.Run(() => + { + var packages = installed.Select(row => row.Package).OfType<VendorPackage>().Distinct(); + foreach (var package in packages.Where(package => !package.KeepAfterInstall)) + package.Delete(); + }); + + // Returns false if the restore point failed and the user chose not to go on without one. + async Task<bool> CreateRestorePointAsync() + { + StatusText.Text = "Creating a restore point"; + string? error; + try + { + error = await Task.Run(() => RestorePoint.Create("Before driver updates")); + } + catch (Exception ex) + { + error = ex.Message; + } + if (error is null) + return true; + + var answer = MessageBox.Show(this, + $"Couldn't create a restore point: {error}\n\nInstall anyway?", + Title, MessageBoxButton.YesNo, MessageBoxImage.Warning); + return answer == MessageBoxResult.Yes; + } + + // This app runs as admin, and a browser started from it would run as admin too. Explorer hands the + // link to the user's normal desktop session instead. + void Link_RequestNavigate(object sender, RequestNavigateEventArgs e) + { + Process.Start("explorer.exe", e.Uri.AbsoluteUri); + e.Handled = true; + } + + void Row_PropertyChanged(object? sender, PropertyChangedEventArgs e) + { + if (e.PropertyName == nameof(DriverUpdate.IsSelected)) + UpdateInstallButton(); + } + + void SetBusy(bool value) + { + busy = value; + ScanButton.IsEnabled = !busy; + BusyBar.Visibility = busy ? Visibility.Visible : Visibility.Collapsed; + UpdateInstallButton(); + } + + void UpdateInstallButton() => InstallButton.IsEnabled = !busy && rows.Any(row => row.IsSelected); +} diff --git a/Nvidia.cs b/Nvidia.cs @@ -0,0 +1,78 @@ +using System.Globalization; +using System.Net.Http.Json; +using System.Text.Json; + +namespace DriverUpdater; + +// Checks NVIDIA for the latest Game Ready driver. This is the lookup the NVIDIA App makes. It takes the +// GPU's PCI IDs and returns the newest driver for that card. +static class Nvidia +{ + const string LookupUrl = "https://gfwsl.geforce.com/nvidia_web_services/controller.gfeclientcontent.NG.php/" + + "com.nvidia.services.GFEClientContent_NG.getDispDrvrByDevid/"; + + public static async Task<List<DriverUpdate>> CheckAsync(IReadOnlyList<InstalledDevice> installed) + { + var updates = new List<DriverUpdate>(); + foreach (var gpu in installed.Where(d => d.DeviceClass == "DISPLAY" && d.IsFromVendor("10DE"))) + updates.Add(await CheckGpuAsync(gpu)); + return updates; + } + + static async Task<DriverUpdate> CheckGpuAsync(InstalledDevice gpu) + { + // NVIDIA wants "DEV_VEN_SUBSYSDEV_SUBSYSVEN", like "2C05_10DE_89F4_1043". + string subsystem = gpu.Field("SUBSYS") ?? ""; + string deviceIds = subsystem.Length == 8 + ? $"{gpu.Field("DEV")}_10DE_{subsystem[..4]}_{subsystem[4..]}" + : $"{gpu.Field("DEV")}_10DE"; + + var query = new + { + dIDa = new[] { deviceIds }, + osC = "10.0", // Windows 10 and 11 both + is6 = "1", // 64 bit + lg = "1033", // English + iLp = "0", // Must be 0. A laptop GPU still gets the notebook driver from its device ID. + dch = "1", + upCRD = "0", // Game Ready. 1 asks for the Studio driver. + }; + string url = LookupUrl + Uri.EscapeDataString(JsonSerializer.Serialize(query)); + var driver = (await Web.Client.GetFromJsonAsync<LookupResponse>(url))!.DriverAttributes; + + string installedVersion = ToNvidiaVersion(gpu.DriverVersion); + bool isNewer = decimal.Parse(driver.Version, CultureInfo.InvariantCulture) + > decimal.Parse(installedVersion, CultureInfo.InvariantCulture); + var packageUrl = new Uri(driver.DownloadURLAdmin); + + return new DriverUpdate + { + Device = gpu.Name, + Source = "NVIDIA", + InstalledVersion = installedVersion, + AvailableVersion = driver.Version, + // Dates look like "2026-10-21T00:00:00+0000", which DateTime won't parse whole. + ReleaseDate = DateTime.ParseExact(driver.ReleaseDateTime[..10], "yyyy-MM-dd", CultureInfo.InvariantCulture), + NotesUrl = new Uri(driver.DetailsURL), + Package = isNewer + ? new VendorPackage(packageUrl, null, "NVIDIA Corporation", VendorPackage.TempFolderFor(packageUrl), Unpack.WithTarAsync) + : null, + TargetDevice = gpu, + Status = isNewer ? "Update available" : "Up to date", + }; + } + + // Windows shows NVIDIA driver 610.88 as 32.0.16.1088. Join the last two fields, keep the last five + // digits, and put the decimal point before the final two. + static string ToNvidiaVersion(string windowsVersion) + { + string[] fields = windowsVersion.Split('.'); + string digits = (fields[2] + fields[3].PadLeft(4, '0'))[^5..]; + return $"{digits[..3]}.{digits[3..]}"; + } + + // The parts of the response the app reads. DownloadURLAdmin is the standard installer. + // DownloadURL is a smaller build meant for the NVIDIA App. + record LookupResponse(DriverAttributes DriverAttributes); + record DriverAttributes(string Version, string ReleaseDateTime, string DetailsURL, string DownloadURLAdmin); +} diff --git a/PnpDriver.cs b/PnpDriver.cs @@ -0,0 +1,39 @@ +using System.ComponentModel; +using System.Runtime.InteropServices; + +namespace DriverUpdater; + +enum DriverInstallResult { Installed, RestartNeeded, NotNewer } + +// Installs a driver INF on the devices it matches, the same way Device Manager's "Update driver" does. +// Windows replaces the current driver only if the new one ranks higher, so this never downgrades. The +// driver store checks the package's signature before it takes the driver. +static class PnpDriver +{ + // Fail instead of showing a dialog. + const uint InstallFlagNonInteractive = 0x4; + + // The INF matched, but Windows ranks the current driver as good or better. + const int ErrorNoMoreItems = 259; + + // SetupAPI's ERROR_NO_SUCH_DEVINST: no device on this PC has the ID. + const int ErrorNoSuchDevice = unchecked((int)0xE000020B); + + public static DriverInstallResult Install(DriverInf inf) + { + if (UpdateDriverForPlugAndPlayDevicesW(IntPtr.Zero, inf.HardwareId, inf.Path, InstallFlagNonInteractive, out bool restartNeeded)) + return restartNeeded ? DriverInstallResult.RestartNeeded : DriverInstallResult.Installed; + + int error = Marshal.GetLastWin32Error(); + return error switch + { + ErrorNoMoreItems => DriverInstallResult.NotNewer, + ErrorNoSuchDevice => throw new InvalidOperationException($"No device here has the ID {inf.HardwareId}"), + _ => throw new Win32Exception(error, $"{new Win32Exception(error).Message} (0x{error:X8})"), + }; + } + + [DllImport("newdev.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] + static extern bool UpdateDriverForPlugAndPlayDevicesW( + IntPtr parentWindow, string hardwareId, string infPath, uint flags, out bool restartNeeded); +} diff --git a/README.md b/README.md @@ -0,0 +1,118 @@ +# Driver Updater + +Finds newer drivers for the hardware in a Windows PC and installs them. It checks Windows Update, then asks NVIDIA, AMD, and Intel directly. It updates only the drivers already in use and installs the driver alone, the way Device Manager's "Update driver" does. No vendor setup program runs and no vendor software gets installed. + +## Requirements + +- Windows 10 or 11, 64 bit. +- Admin rights. The app asks for them at startup because installing drivers and creating restore points both need them. +- 7-Zip, only for AMD chipset drivers. Without it the chipset row says to install it, and everything else still works. +- The .NET 10 SDK to build. The published exe runs without .NET installed. + +The app has no NuGet dependencies. WMI and Windows Update are COM objects called through `dynamic`. + +## Build and run + +From the repo folder in an elevated terminal: + +```powershell +dotnet run +``` + +From a normal terminal, `dotnet run` fails with "The requested operation requires elevation". Build it and start the exe instead. Windows shows the UAC prompt. + +```powershell +dotnet build +start bin\Debug\net10.0-windows\DriverUpdater.exe +``` + +To build one exe that carries the .NET runtime (about 62 MB): + +```powershell +dotnet publish -c Release +``` + +It lands in `bin\Release\net10.0-windows\win-x64\publish\DriverUpdater.exe`. + +From WSL, run the same commands with `dotnet.exe` so the Windows SDK does the build. + +## Where updates come from + +| Source | Devices | Lookup | Installs | +|---|---|---|---| +| Windows Update | Anything Microsoft has a driver for | Windows Update Agent API, searching Microsoft's servers for `Type='Driver'` | Yes | +| NVIDIA | GeForce GPUs | `getDispDrvrByDevid` on `gfwsl.geforce.com`, keyed by PCI device ID | Yes | +| AMD graphics | Radeon GPUs and Ryzen integrated graphics | `drivers.amd.com/drivers/installer/json/version.json` and the feeds it lists | Yes | +| AMD chipset | Devices already on an AMD chipset driver | `drivers.amd.com/drivers/installer/chipset/VersionInfo.xml`, then the INFs in the package | Yes, with 7-Zip | +| Intel | Graphics, wireless, and Ethernet | The Intel Driver & Support Assistant catalog at `dsadata.intel.com/data/en` | No. Rows link to Intel's page | + +Each vendor endpoint is the one that vendor's own update tool calls. None of them is documented. Any of them can change without notice. AMD's server needs an amd.com `Referer`. Intel's needs a `User-Agent`. The app sends both. + +Intel is check only because Intel packs graphics, Wi-Fi, and Bluetooth drivers in three different installer formats. Unpacking each needs its own code, and that needs Intel hardware to test on. + +## How it installs + +Windows Update drivers download and install silently through the Windows Update Agent API. + +Vendor drivers go through five steps: + +1. **Download.** The vendor's package goes to `%TEMP%\DriverUpdater`. A dropped download is retried twice. +2. **Signature.** `WinVerifyTrust` checks the Authenticode signature, revocation included. The signer has to be `NVIDIA Corporation` or `Advanced Micro Devices` to match the source. If either check fails, the file is deleted. +3. **Unpack.** NVIDIA's and AMD's graphics packages are 7z archives, which the `tar.exe` built into Windows reads. AMD's chipset package is an NSIS installer holding an InstallShield setup. 7-Zip opens the NSIS layer. The InstallShield layer unpacks itself through an MSI administrative install, which copies files out and installs nothing. AMD's own installer unpacks it the same way. +4. **Find the INF.** The app looks for the INF that lists the device's most specific hardware ID, then its compatible IDs. IDs that only name a device class are skipped. +5. **Install.** `UpdateDriverForPlugAndPlayDevices` installs that INF on the device with no UI and waits for it to finish. Windows replaces the driver only if it ranks the new one higher, so this never downgrades. The driver store checks the package's own signature. + +Graphics packages unpack to 2 to 4 GB, so they're deleted after the install. The chipset package stays in `%LOCALAPPDATA%\DriverUpdater`, one folder per AMD release, because every scan reads it. + +Before installing anything, the app creates a System Restore point. Clear the checkbox to skip it. + +## How versions are compared + +Each vendor numbers drivers differently from Windows. + +- **NVIDIA:** Windows shows driver 610.88 as `32.0.16.1088`. The app joins the last two fields, keeps the last five digits, and compares the result with NVIDIA's version. +- **AMD graphics:** the Windows version doesn't map cleanly to Adrenalin releases. The app reads AMD's internal build (`25.10.42`) from `ReleaseVersion` in the GPU's driver registry key. The display INF writes that value, so it stays right after a driver only install. The Available column shows both numbers, as in `26.10.1 (25.10.45)`. +- **AMD chipset:** each device is compared the way Windows ranks drivers. An INF that matches an earlier ID in the device's list wins. On a tie, the newer date wins, then the higher version. `MatchingDeviceId` in the driver key says which ID the installed driver matched. Only devices whose current driver comes from AMD are compared. +- **Intel:** the Windows driver version against the catalog's component version. +- **Windows Update:** the API has no version field. Available shows the version from the end of the update title when there is one. + +## When something fails + +| What you see | Cause | Fix | +|---|---|---| +| `Windows Update error 0x80240044` | The app isn't running as admin | Start it through UAC | +| `Windows Update error 0x8024402C` | Windows Update can't reach Microsoft | Check the network and proxy | +| `Couldn't create a restore point` | System Protection is off for the system drive | Turn it on in System Properties, or clear the checkbox | +| A row like `NVIDIA check` with `Failed: ...` | The vendor changed or blocked its endpoint, or doesn't know the device | Hover the status for the full error | +| `The download isn't signed by ..., so it was deleted` | The download's signature is invalid or belongs to someone else | Get the driver from the vendor's site | +| `tar.exe failed` or `7z.exe failed` | The vendor changed its package format | Hover the status for the tool's error | +| `Nothing in the package matches this device` | The package has no INF listing any of the device's IDs | The vendor dropped the device, or the feed picked the wrong package | +| `Windows kept the current driver` | Windows ranks the installed driver as good or better | Nothing to do | +| `Install 7-Zip to check these` | AMD chipset drivers need 7-Zip to unpack | Install 7-Zip and scan again | + +Windows quietly skips a restore point if it made one in the last 24 hours. The app counts that as success. + +## Limits + +- Only the GPU itself gets the new graphics driver. The GPU's HDMI audio device keeps its current driver. +- AMD Software, the Adrenalin app, stays at its old version after a driver only install. It can warn that it doesn't match the driver. +- The NVIDIA lookup asks for the Game Ready driver. Someone on the Studio driver gets offered Game Ready. The version number doesn't say which one is installed. +- AMD PRO drivers for workstation cards aren't checked. +- A chipset scan runs AMD's signed InstallShield setup in administrative mode to unpack a new release, before anything is selected. It installs nothing. + +## Files + +| File | What it does | +|---|---| +| `MainWindow.xaml`, `MainWindow.xaml.cs` | The window, the scan, and the install loop | +| `InstalledDevices.cs` | Reads devices, driver versions, and device IDs from WMI | +| `WindowsUpdate.cs` | Searches, downloads, and installs through the Windows Update Agent API | +| `Nvidia.cs`, `Amd.cs`, `Intel.cs` | One vendor check each | +| `VendorPackage.cs` | Downloads, verifies, and unpacks a vendor package once for every row that needs it | +| `Unpack.cs` | Runs `tar.exe`, 7-Zip, and other unpacking tools | +| `DriverInf.cs` | Finds the INF for a device and ranks it against the installed driver | +| `PnpDriver.cs` | Installs an INF through `UpdateDriverForPlugAndPlayDevices` | +| `Authenticode.cs` | The signature check | +| `RestorePoint.cs` | Creates the restore point through WMI | +| `DriverUpdate.cs` | One row in the list | +| `Com.cs`, `Web.cs` | COM object creation and the shared `HttpClient` | diff --git a/RestorePoint.cs b/RestorePoint.cs @@ -0,0 +1,21 @@ +using System.ComponentModel; + +namespace DriverUpdater; + +// Creates a System Restore point, so a bad driver can be rolled back from Windows recovery. +static class RestorePoint +{ + // Argument values for SystemRestore.CreateRestorePoint. + const int DeviceDriverInstall = 10; + const int BeginSystemChange = 100; + + // Returns null on success, or why it failed. Windows quietly skips the restore point if it made + // one in the last 24 hours, and that still counts as success. + public static string? Create(string description) + { + dynamic locator = Com.Create("WbemScripting.SWbemLocator"); + dynamic systemRestore = locator.ConnectServer(".", @"root\default").Get("SystemRestore"); + int code = systemRestore.CreateRestorePoint(description, DeviceDriverInstall, BeginSystemChange); + return code == 0 ? null : new Win32Exception(code).Message; + } +} diff --git a/Unpack.cs b/Unpack.cs @@ -0,0 +1,53 @@ +using System.Diagnostics; +using System.IO; +using Microsoft.Win32; + +namespace DriverUpdater; + +// Runs the tools that unpack vendor packages, so the app can install the drivers inside without +// running the vendor's setup. +static class Unpack +{ + // The tar.exe built into Windows reads 7z archives, including the ones behind a small exe like + // NVIDIA's and AMD's graphics packages. + public static Task WithTarAsync(string package, string folder) + { + Directory.CreateDirectory(folder); + string tar = Path.Combine(Environment.SystemDirectory, "tar.exe"); + return RunAsync(tar, $"-xf \"{package}\" -C \"{folder}\""); + } + + // 7-Zip is optional. Only AMD's chipset package needs it. + public static string? SevenZipPath() + { + using var hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); + using var key = hklm.OpenSubKey(@"SOFTWARE\7-Zip"); + if ((key?.GetValue("Path64") ?? key?.GetValue("Path")) is not string folder) + return null; + + string sevenZip = Path.Combine(folder, "7z.exe"); + return File.Exists(sevenZip) ? sevenZip : null; + } + + // Runs a tool with no window, waits for it, and throws with its error output if it fails. Both + // output streams are read at once, so a tool that fills one can't stall waiting on the other. + public static async Task RunAsync(string exe, string arguments) + { + var start = new ProcessStartInfo(exe, arguments) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + using var process = Process.Start(start)!; + var output = process.StandardOutput.ReadToEndAsync(); + string errors = await process.StandardError.ReadToEndAsync(); + await output; + await process.WaitForExitAsync(); + + if (process.ExitCode != 0) + throw new InvalidOperationException( + $"{Path.GetFileName(exe)} failed with exit code {process.ExitCode}. {errors.Trim()}".Trim()); + } +} diff --git a/VendorPackage.cs b/VendorPackage.cs @@ -0,0 +1,113 @@ +using System.IO; +using System.Net.Http; + +namespace DriverUpdater; + +// A vendor's driver package. It's downloaded, signature checked, and unpacked the first time a row +// needs it. Every row that installs from it then shares the unpacked folder. +sealed class VendorPackage(Uri url, Uri? referrer, string signer, string folder, Func<string, string, Task> unpack) +{ + Task<string>? unpacked; + + // Packages normally unpack to the temp folder and get deleted after the install. AMD's chipset + // package is kept, because each scan reads its INFs to compare versions. + public bool KeepAfterInstall { get; init; } + + public static string TempFolderFor(Uri url) => + Path.Combine(Path.GetTempPath(), "DriverUpdater", Path.GetFileNameWithoutExtension(url.LocalPath)); + + // Returns the unpacked folder. Rows that share the package wait on the same download. + public async Task<string> UnpackAsync(Action<string> status) + { + unpacked ??= DownloadAndUnpackAsync(status); + try + { + return await unpacked; + } + catch + { + unpacked = null; + throw; + } + } + + public void Delete() + { + unpacked = null; + if (Directory.Exists(folder)) + Directory.Delete(folder, recursive: true); + } + + async Task<string> DownloadAndUnpackAsync(Action<string> status) + { + // A finished unpack gets moved into place last, so an existing folder is a complete one. + if (Directory.Exists(folder)) + return folder; + + string parent = Path.GetDirectoryName(folder)!; + Directory.CreateDirectory(parent); + string download = Path.Combine(parent, Path.GetFileName(url.LocalPath)); + string partial = folder + ".partial"; + try + { + await DownloadAsync(download, status); + + status("Checking signature"); + if (!await Task.Run(() => Authenticode.IsSignedBy(download, signer))) + throw new InvalidOperationException($"The download isn't signed by {signer}, so it was deleted"); + + status("Unpacking"); + if (Directory.Exists(partial)) + Directory.Delete(partial, recursive: true); + await unpack(download, partial); + Directory.Move(partial, folder); + return folder; + } + finally + { + File.Delete(download); + if (Directory.Exists(partial)) + Directory.Delete(partial, recursive: true); + } + } + + // Big downloads sometimes drop partway. Try three times before giving up. + async Task DownloadAsync(string path, Action<string> status) + { + for (int attempt = 1; ; attempt++) + { + try + { + await DownloadOnceAsync(path, status); + return; + } + catch (Exception ex) when (attempt < 3 && ex is HttpRequestException or IOException or TaskCanceledException) + { + status($"Download failed, retrying: {ex.Message}"); + await Task.Delay(TimeSpan.FromSeconds(5 * attempt)); + } + } + } + + async Task DownloadOnceAsync(string path, Action<string> status) + { + using var request = new HttpRequestMessage(HttpMethod.Get, url) { Headers = { Referrer = referrer } }; + using var response = await Web.Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); + response.EnsureSuccessStatusCode(); + long? totalBytes = response.Content.Headers.ContentLength; + + await using var source = await response.Content.ReadAsStreamAsync(); + await using var target = File.Create(path); + var buffer = new byte[1 << 20]; + long receivedBytes = 0; + int read; + while ((read = await source.ReadAsync(buffer)) > 0) + { + await target.WriteAsync(buffer.AsMemory(0, read)); + receivedBytes += read; + status(totalBytes > 0 + ? $"Downloading {receivedBytes * 100 / totalBytes.Value}%" + : $"Downloading {receivedBytes / 1_048_576} MB"); + } + } +} diff --git a/Web.cs b/Web.cs @@ -0,0 +1,13 @@ +using System.Net.Http; + +namespace DriverUpdater; + +static class Web +{ + // Shared by the vendor checks and the installer downloads. Intel's catalog rejects requests + // with no User-Agent. + public static readonly HttpClient Client = new() + { + DefaultRequestHeaders = { { "User-Agent", "DriverUpdater/0.1" } }, + }; +} diff --git a/WindowsUpdate.cs b/WindowsUpdate.cs @@ -0,0 +1,91 @@ +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; + +namespace DriverUpdater; + +// Finds and installs driver updates through the Windows Update Agent API, the same API the Settings +// app uses. These are drivers the vendors submitted to Microsoft and Microsoft signed. It's all COM, +// called through dynamic so the project needs no interop assembly. +static partial class WindowsUpdate +{ + // ServerSelection value that asks Microsoft's servers directly, even on a machine managed by WSUS. + const int ServerSelectionWindowsUpdate = 2; + + // OperationResultCode values. + const int Succeeded = 2; + const int SucceededWithErrors = 3; + + public static List<DriverUpdate> Search(IReadOnlyList<InstalledDevice> installed) + { + dynamic session = Com.Create("Microsoft.Update.Session"); + dynamic searcher = session.CreateUpdateSearcher(); + searcher.ServerSelection = ServerSelectionWindowsUpdate; + dynamic result = searcher.Search("IsInstalled=0 and IsHidden=0 and Type='Driver'"); + + var updates = new List<DriverUpdate>(); + foreach (dynamic update in result.Updates) + { + string hardwareId = update.DriverHardwareID; + string title = update.Title; + var device = installed.FirstOrDefault(d => + d.HardwareIds.Contains(hardwareId, StringComparer.OrdinalIgnoreCase)); + + updates.Add(new DriverUpdate + { + Device = update.DriverModel, + Source = "Windows Update", + InstalledVersion = device?.DriverVersion ?? "", + AvailableVersion = VersionAtEndOfTitle().Match(title).Groups[1].Value, + ReleaseDate = update.DriverVerDate, + SizeBytes = (long)(decimal)update.MaxDownloadSize, + WindowsUpdateItem = update, + Status = "Update available", + }); + } + return updates; + } + + public static void Download(dynamic update) + { + dynamic session = Com.Create("Microsoft.Update.Session"); + dynamic downloader = session.CreateUpdateDownloader(); + downloader.Updates = SingleUpdateCollection(update); + ThrowIfFailed(downloader.Download()); + } + + // Returns true if Windows needs a restart to finish the install. + public static bool Install(dynamic update) + { + if (!update.EulaAccepted) + update.AcceptEula(); + + dynamic session = Com.Create("Microsoft.Update.Session"); + dynamic installer = session.CreateUpdateInstaller(); + installer.Updates = SingleUpdateCollection(update); + dynamic result = installer.Install(); + ThrowIfFailed(result); + return result.RebootRequired; + } + + static dynamic SingleUpdateCollection(dynamic update) + { + dynamic collection = Com.Create("Microsoft.Update.UpdateColl"); + collection.Add(update); + return collection; + } + + static void ThrowIfFailed(dynamic result) + { + int code = result.ResultCode; + if (code is Succeeded or SucceededWithErrors) + return; + + int hresult = result.GetUpdateResult(0).HResult; + throw new COMException($"Windows Update error 0x{hresult:X8}", hresult); + } + + // Driver update titles usually end with the version, as in "NVIDIA - Display - 32.0.15.6094" + // or "Apple, Inc. USBDevice Driver Update (552.0.0.0)". The API has no version field. + [GeneratedRegex(@"(\d+(?:\.\d+){1,3})\)?$")] + private static partial Regex VersionAtEndOfTitle(); +} diff --git a/app.manifest b/app.manifest @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="utf-8"?> +<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1"> + <assemblyIdentity version="1.0.0.0" name="DriverUpdater.app" /> + + <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> + <security> + <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> + <!-- Installing drivers and creating restore points both need admin. --> + <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> + </requestedPrivileges> + </security> + </trustInfo> + + <application xmlns="urn:schemas-microsoft-com:asm.v3"> + <windowsSettings> + <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness> + </windowsSettings> + </application> +</assembly>