跳到主要内容

GeneralUpdate.Drivelution

命名空间: GeneralUpdate.Drivelution | 主要入口: GeneralDrivelution(静态类) | NuGet 包: GeneralUpdate.Drivelution

1. 组件简介

1.1 组件概述

GeneralUpdate.Drivelution 是面向驱动更新场景的跨平台组件。它把驱动更新中容易出错的步骤拆成统一流水线:平台识别 → 权限检查 → 文件验证(哈希/签名/兼容性) → 备份 → 安装 → 结果验证 → 失败后回滚,并在 Windows、Linux、macOS 上分别调用系统原生工具完成驱动安装。

驱动更新不是普通应用文件替换。应用文件通常只需要下载、解压、覆盖并重启进程;驱动更新会影响内核、设备节点、系统扩展或驱动仓库,因此必须额外关注管理员权限、签名可信度、目标系统和 CPU 架构、安装命令返回值、是否需要系统重启以及失败后的恢复路径。

核心能力:

能力说明
跨平台抽象GeneralDrivelution.Create() 自动检测平台(Windows/Linux/macOS)创建对应实现
标准更新流水线权限检查 → 文件验证(存在/哈希/签名/兼容性) → 备份 → 安装 → 验证 → 失败回滚
文件验证文件存在检查、SHA256/MD5 哈希校验、Authenticode/GPG/codesign 签名校验、OS/架构兼容性检查
备份与回滚RequireBackup 默认为 true,失败后自动回滚并保留备份路径供业务显式调用 RollbackAsync
Windows 安装通过 pnputil.exe /add-driver /install 安装 INF 驱动包
Linux 安装支持 .koinsmod/modprobe)、.debdpkg -i)、.rpmrpm -ivh/dnf install
macOS 安装支持 .kextkextload)、.dext(SystemExtensions)、.pkginstaller
批量更新BatchUpdateAsync 支持 BatchMode.SequentialBatchMode.Parallel
进度报告通过 IProgress<UpdateProgress> 上报各步骤的进度、状态和消息
日志追踪GeneralTracer 默认控制台 + 按日期轮转文件输出

解决的业务痛点:

  • 硬件厂商客户端需要随应用交付驱动更新,但不同 OS 驱动安装方式差异大
  • 驱动安装需要管理员权限、签名校验、架构兼容性检查等多重保障
  • 驱动安装失败后需要可靠的回滚机制,避免设备不可用

业务使用场景:

  • 硬件厂商客户端:网卡、采集卡、USB 设备、虚拟设备驱动随应用一起交付
  • 企业/工业现场:批量扫描驱动包并按清单更新
  • 安装器/维护工具:统一处理 Windows/Linux/macOS 驱动差异
驱动更新 ≠ 普通文件替换

驱动更新会影响内核、设备节点、系统扩展或驱动仓库。必须关注:管理员权限、签名可信度、目标系统和 CPU 架构、安装命令返回值、是否需要系统重启以及失败后的恢复路径。生产环境中永远不要跳过哈希和签名校验。

1.2 环境与依赖

项目说明
版本10.5.0-beta.2
目标框架net8.0 / net10.0(多目标)
依赖包Microsoft.Extensions.DependencyInjectionMicrosoft.Extensions.Logging.AbstractionsMicrosoft.Extensions.Options
兼容性Windows(完整支持,需管理员权限)/ Linux(需 root/sudo)/ macOS(受 SIP 和系统扩展策略影响)

2. 组件功能列表

功能名称功能描述类型是否必填备注限制
单驱动快速更新QuickUpdateAsync 使用默认策略快速更新单个驱动基础可选推荐生产环境使用自定义策略
自定义策略更新UpdateAsync 配合 UpdateStrategyDrivelutionOptions基础推荐可控制备份、重试、超时、重启策略
驱动验证文件存在、SHA256 哈希、签名、OS/架构兼容性检查基础可选ValidateAsync,可通过策略跳过部分校验
驱动备份更新前备份驱动文件到指定路径基础自动RequireBackup 默认为 true
驱动回滚从备份路径恢复驱动基础可选RollbackAsync(backupPath)
目录扫描从目录扫描并解析驱动信息(.inf/.ko/.kext 等)基础可选GetDriversFromDirectoryAsync
批量更新按清单批量更新,支持顺序/并行模式拓展可选BatchUpdateAsync
平台信息查询获取当前 OS/架构/版本/是否支持基础可选GetPlatformInfo()
重启行为控制UpdateStrategy.RestartMode 设定重启意图拓展可选更新流水线不会自动重启,需业务层调用 RestartHelper
DI 注册AddDrivelution 扩展方法注册平台服务拓展可选支持 Generic Host / ASP.NET Core
日志追踪GeneralTracer 运行时诊断日志拓展可选默认开启,可关闭

3. API 配置说明

3.1 配置字段(属性 Props)

DriverInfo:

字段名数据类型默认值是否必填枚举/取值范围说明
Namestring""驱动名称
Versionstring""推荐SemVer 格式驱动版本,扫描目录时会尽量从元数据读取
FilePathstring""有效文件路径Windows: .inf;Linux: .ko/.deb/.rpm;macOS: .kext/.dext/.pkg
TargetOSstring""可选"Windows", "Linux", "MacOS"为空时不限制 OS
Architecturestring""可选"x64"/"amd64"/"x86"/"arm64"/"arm"支持常见别名归一化;为空不限制
HardwareIdstring""可选硬件 ID 或模块别名
Hashstring""可选SHA256/MD5 哈希值非空且 SkipHashValidation = false 时执行哈希校验
HashAlgorithmstring"SHA256"可选"SHA256" / "MD5"哈希算法
TrustedPublishersList<string>new()可选可信发布者列表,非空且未跳过签名校验时验证签名
Descriptionstring""可选驱动描述
ReleaseDateDateTime可选发布时间
MetadataDictionary<string, string>new()可选扩展元数据

UpdateStrategy:

字段名数据类型默认值是否必填枚举/取值范围说明
RequireBackupbooltrue可选true / false是否执行备份步骤
BackupPathstring""推荐有效目录路径备份根路径,流水线在该路径下生成 backup_{Name}_{yyyyMMddHHmmss}
RestartModeRestartModePrompt可选None, Prompt, Delayed, Immediate重启意图,流水线不会自动重启系统
SkipHashValidationboolfalse可选true / false跳过哈希校验(仅调试/受控环境)
SkipSignatureValidationboolfalse可选true / false跳过签名校验(仅调试/受控环境)
TimeoutSecondsint300可选正整数单次更新超时,≤0 时使用 DrivelutionOptions.DefaultTimeoutSeconds
RetryCountint3可选正整数重试次数(策略字段,实际重试来自 DrivelutionOptions
RetryIntervalSecondsint5可选正整数重试间隔秒数
ModeUpdateModeFull可选Full, Incremental更新模式
ForceUpdateboolfalse可选true / false是否强制更新
Priorityint0可选优先级

DrivelutionOptions:

字段名数据类型默认值是否必填说明
DefaultBackupPathstring"./DriverBackups"可选默认备份路径
DefaultRetryCountint3可选默认重试次数
DefaultRetryIntervalSecondsint5可选默认重试间隔
DefaultTimeoutSecondsint300可选默认超时时间
DebugModeSkipSignatureboolfalse可选调试模式跳过签名
DebugModeSkipHashboolfalse可选调试模式跳过哈希
ForceTerminateOnPermissionFailurebooltrue可选权限失败时立即终止
AutoCleanupBackupsbooltrue可选自动清理旧备份
BackupsToKeepint5可选保留备份数量
UseExponentialBackoffboolfalse可选是否使用指数退避

3.2 实例方法

GeneralDrivelution(静态类):

方法名入参明细使用场景注意事项
Create(DrivelutionOptions?)options — 全局选项创建当前平台的驱动更新器自动检测平台
Create(IServiceProvider)serviceProvider — DI 容器从 DI 容器解析未注册时回退到自动平台创建
QuickUpdateAsync(DriverInfo, UpdateStrategy?, IProgress<UpdateProgress>?, CancellationToken)driverInfo — 驱动信息;strategy — 可选策略(null 时使用默认);progress — 进度报告;ct — 取消令牌快速单驱动更新使用安全默认策略
ValidateAsync(DriverInfo, CancellationToken)driverInfo — 驱动信息;ct — 取消令牌单独验证驱动文件
GetPlatformInfo()查询当前平台信息返回 OS/架构/版本/是否支持
GetDriversFromDirectoryAsync(string, string?, CancellationToken)directoryPath — 目录路径;searchPattern — 搜索模式;ct — 取消令牌扫描目录解析驱动信息默认搜索模式与平台相关
BatchUpdateAsync(IEnumerable<DriverInfo>, UpdateStrategy, BatchMode, IProgress<UpdateProgress>?, CancellationToken)drivers — 驱动列表;strategy — 更新策略;mode — 顺序/并行;progress — 进度;ct — 取消令牌批量更新多个驱动并行模式下底层系统工具可能竞争资源

IGeneralDrivelution:

方法名入参明细使用场景注意事项
UpdateAsync(...)QuickUpdateAsync执行完整更新流水线
ValidateAsync(...)GeneralDrivelution.ValidateAsync单独验证
BackupAsync(DriverInfo, string, CancellationToken)driverInfo, backupPath, ct单独备份驱动文件
RollbackAsync(string, CancellationToken)backupPath — 备份路径;ct — 取消令牌从备份恢复驱动不同平台恢复逻辑不同
GetDriversFromDirectoryAsync(...)GeneralDrivelution扫描目录
BatchUpdateAsync(...)GeneralDrivelution批量更新

3.3 回调事件

Drivelution 通过 IProgress<UpdateProgress> 报告进度,不提供独立的事件系统。

进度字段类型说明
CurrentStatusUpdateStatus当前状态(Validating/BackingUp/Updating/Verifying/Succeeded/Failed/RolledBack
StepNamestring当前步骤名称
Percentageint进度百分比 (0-100)
Messagestring进度消息
StepIndexint当前步骤索引
TotalStepsint总步骤数

4. 扩展示例(高阶用法)

4.1 组件可扩展能力总览

扩展接口说明
IGeneralDrivelution完整替换驱动更新器的所有行为
IDriverValidator自定义文件验证逻辑
IDriverBackup自定义备份/恢复策略
ICommandRunner自定义系统命令执行器
INetworkDownloader预留接口(网络下载)
BaseDriverUpdater抽象基类,可继承创建新平台实现

4.2 分场景示例

场景 1:自定义策略 + 回滚处理

【场景说明】生产环境驱动更新,启用所有安全检查,失败时显式回滚。

【示例代码】

using GeneralUpdate.Drivelution;
using GeneralUpdate.Drivelution.Abstractions.Configuration;
using GeneralUpdate.Drivelution.Abstractions.Models;

var options = new DrivelutionOptions
{
DefaultBackupPath = @"C:\DriverBackups",
DefaultRetryCount = 3,
DefaultRetryIntervalSeconds = 5,
DefaultTimeoutSeconds = 600,
UseExponentialBackoff = true,
ForceTerminateOnPermissionFailure = true
};

var updater = GeneralDrivelution.Create(options);

var strategy = new UpdateStrategy
{
RequireBackup = true,
BackupPath = @"C:\DriverBackups\graphics",
TimeoutSeconds = 600,
RestartMode = RestartMode.Prompt,
SkipHashValidation = false,
SkipSignatureValidation = false
};

var driver = new DriverInfo
{
Name = "Graphics Driver",
Version = "2.1.0",
FilePath = @"C:\Drivers\graphics.inf",
TargetOS = "Windows",
Architecture = "x64",
Hash = "expected-sha256...",
HashAlgorithm = "SHA256",
TrustedPublishers = { "Contoso Hardware Inc." }
};

var progress = new Progress<UpdateProgress>(p =>
{
Console.WriteLine($"[{p.StepName}] {p.Percentage}%: {p.Message}");
});

var result = await updater.UpdateAsync(driver, strategy, progress);

if (!result.Success)
{
Console.WriteLine($"Update failed: {result.Error?.Message}");

if (result.BackupPath is not null)
{
Console.WriteLine("Rolling back...");
await updater.RollbackAsync(result.BackupPath);
}
}
else if (RestartHelper.IsRestartRequired(strategy.RestartMode))
{
await RestartHelper.HandleRestartAsync(
strategy.RestartMode,
delaySeconds: 60,
message: "Driver updated. Restart now?");
}

【效果&注意事项】

  • 生产环境不要跳过哈希和签名校验
  • 回滚后驱动恢复到安装前状态,但仍建议提示用户可能需要重启

场景 2:DI 容器集成

【场景说明】在 ASP.NET Core / Generic Host 应用中通过 DI 注册驱动更新服务。

【示例代码】

using GeneralUpdate.Drivelution.Core;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDrivelution(options =>
{
options.DefaultBackupPath = "./DriverBackups";
options.DefaultTimeoutSeconds = 600;
options.DefaultRetryCount = 3;
options.AutoCleanupBackups = true;
options.BackupsToKeep = 5;
});

var app = builder.Build();

// 在 Controller 或 Service 中使用
app.MapPost("/drivers/update", async (DriverInfo driver, IGeneralDrivelution updater) =>
{
var result = await updater.UpdateAsync(driver, new UpdateStrategy());
return result.Success ? Results.Ok(result) : Results.BadRequest(result.Error);
});

【效果&注意事项】

  • AddDrivelution 自动注册平台对应的所有服务
  • 支持通过 IServiceProvider 创建:GeneralDrivelution.Create(serviceProvider)

场景 3:批量并行扫描 + 顺序安装

【场景说明】大型项目先并行扫描验证所有驱动,再按风险分组顺序安装。

【示例代码】

using GeneralUpdate.Drivelution;
using GeneralUpdate.Drivelution.Abstractions.Models;

// 1. 并行扫描和验证所有驱动
var drivers = await GeneralDrivelution.GetDriversFromDirectoryAsync(@"C:\DriverPackages");

var compatibleDrivers = new List<DriverInfo>();
foreach (var driver in drivers)
{
var valid = await GeneralDrivelution.ValidateAsync(driver);
if (valid)
{
Console.WriteLine($"{driver.Name} v{driver.Version}: valid");
compatibleDrivers.Add(driver);
}
else
{
Console.WriteLine($"{driver.Name} v{driver.Version}: INVALID, skipping");
}
}

// 2. 按风险分组
var coreDrivers = compatibleDrivers
.Where(d => d.Metadata.ContainsKey("RiskLevel") && d.Metadata["RiskLevel"] == "Core")
.ToList();

var optionalDrivers = compatibleDrivers
.Except(coreDrivers)
.ToList();

// 3. 核心驱动顺序安装
if (coreDrivers.Any())
{
var coreResult = await GeneralDrivelution.BatchUpdateAsync(
coreDrivers,
new UpdateStrategy { RequireBackup = true },
BatchMode.Sequential); // 顺序安装,降低风险

Console.WriteLine($"Core drivers: {coreResult.SucceededCount}/{coreResult.SucceededCount + coreResult.FailedCount}");
}

// 4. 可选驱动并行安装
if (optionalDrivers.Any())
{
var optResult = await GeneralDrivelution.BatchUpdateAsync(
optionalDrivers,
new UpdateStrategy { RequireBackup = true },
BatchMode.Parallel); // 互不依赖,并行安装

Console.WriteLine($"Optional drivers: {optResult.SucceededCount}/{optResult.SucceededCount + optResult.FailedCount}");
}

【效果&注意事项】

  • BatchMode.Parallel 不一定更快,底层系统工具可能竞争驱动仓库锁
  • 核心驱动建议顺序安装,降低系统风险

5. 常规使用示例

5.1 快速入门示例(最简 demo)

using GeneralUpdate.Drivelution;
using GeneralUpdate.Drivelution.Abstractions.Models;

var driver = new DriverInfo
{
Name = "MyDevice Driver",
Version = "1.2.0",
FilePath = @"C:\Drivers\mydevice.inf",
TargetOS = "Windows",
Architecture = "x64",
Hash = "driver-file-sha256",
HashAlgorithm = "SHA256",
TrustedPublishers = { "Contoso Hardware" }
};

var result = await GeneralDrivelution.QuickUpdateAsync(driver);

if (result.Success)
Console.WriteLine($"Driver updated successfully in {result.DurationMs}ms.");
else
{
Console.WriteLine($"Update failed: {result.Error?.Message}");
foreach (var log in result.StepLogs)
Console.WriteLine($" {log}");
}

5.2 基础参数组合示例

using GeneralUpdate.Drivelution;
using GeneralUpdate.Drivelution.Abstractions.Configuration;
using GeneralUpdate.Drivelution.Abstractions.Models;

// 查询平台信息
var platform = GeneralDrivelution.GetPlatformInfo();
Console.WriteLine($"OS: {platform.OperatingSystem}, Arch: {platform.Architecture}");

// 扫描驱动目录
var drivers = await GeneralDrivelution.GetDriversFromDirectoryAsync(@"C:\Drivers");
Console.WriteLine($"Found {drivers.Count} driver(s).");

foreach (var d in drivers)
Console.WriteLine($" {d.Name} v{d.Version} ({d.FilePath})");

// 创建更新器
var updater = GeneralDrivelution.Create(new DrivelutionOptions
{
DefaultBackupPath = @"C:\DriverBackups",
DefaultRetryCount = 3,
DefaultTimeoutSeconds = 600
});

// 更新,带进度
var progress = new Progress<UpdateProgress>(p =>
Console.WriteLine($"{p.StepName}: {p.Percentage}%"));

var strategy = new UpdateStrategy
{
RequireBackup = true,
BackupPath = @"C:\DriverBackups\mydevice",
TimeoutSeconds = 300
};

var result = await updater.UpdateAsync(drivers[0], strategy, progress);
Console.WriteLine($"Result: {(result.Success ? "Success" : "Failed")}");

if (result.Success && RestartHelper.IsRestartRequired(strategy.RestartMode))
await RestartHelper.HandleRestartAsync(strategy.RestartMode, 60);

5.3 真实业务落地示例

完整驱动更新工作流,覆盖扫描、验证、安装、回滚、重启:

using GeneralUpdate.Drivelution;
using GeneralUpdate.Drivelution.Abstractions.Configuration;
using GeneralUpdate.Drivelution.Abstractions.Models;

// 1. 全局配置
var options = new DrivelutionOptions
{
DefaultBackupPath = @"C:\ProgramData\MyProduct\DriverBackups",
DefaultRetryCount = 2,
DefaultRetryIntervalSeconds = 10,
DefaultTimeoutSeconds = 900,
UseExponentialBackoff = true,
ForceTerminateOnPermissionFailure = true,
AutoCleanupBackups = true,
BackupsToKeep = 3
};

// 2. 创建更新器
var updater = GeneralDrivelution.Create(options);

// 3. 扫描驱动目录
var platform = GeneralDrivelution.GetPlatformInfo();
Console.WriteLine($"Running on {platform.OperatingSystem} {platform.Architecture}");

var drivers = await GeneralDrivelution.GetDriversFromDirectoryAsync(
@"C:\ProgramData\MyProduct\DriverPackages");

var compatible = drivers
.Where(d => string.IsNullOrEmpty(d.TargetOS) || d.TargetOS == platform.OperatingSystem)
.ToList();

Console.WriteLine($"Found {drivers.Count} driver(s), {compatible.Count} compatible.");

// 4. 逐驱动验证并更新
var results = new List<(DriverInfo Driver, UpdateResult Result)>();
foreach (var driver in compatible)
{
// 先验证
var valid = await GeneralDrivelution.ValidateAsync(driver);
if (!valid)
{
Console.WriteLine($"[SKIP] {driver.Name}: validation failed");
continue;
}

// 再更新
var strategy = new UpdateStrategy
{
RequireBackup = true,
BackupPath = Path.Combine(options.DefaultBackupPath, driver.Name),
TimeoutSeconds = 600,
RestartMode = RestartMode.Prompt,
SkipHashValidation = false,
SkipSignatureValidation = false
};

var progress = new Progress<UpdateProgress>(p =>
{
if (p.Percentage % 25 == 0 || p.CurrentStatus == UpdateStatus.Succeeded)
Console.WriteLine($"[{driver.Name}] {p.StepName} {p.Percentage}%: {p.Message}");
});

var result = await updater.UpdateAsync(driver, strategy, progress);
results.Add((driver, result));

if (!result.Success)
{
Console.WriteLine($"[FAIL] {driver.Name}: {result.Error?.Message}");
if (result.BackupPath != null)
{
Console.WriteLine($" Rolling back {driver.Name}...");
await updater.RollbackAsync(result.BackupPath);
}
}
else
{
Console.WriteLine($"[OK] {driver.Name} v{driver.Version} ({result.DurationMs}ms)");
}
}

// 5. 汇总并处理重启
var succeeded = results.Count(r => r.Result.Success);
var failed = results.Count(r => !r.Result.Success);
Console.WriteLine($"\nSummary: {succeeded} succeeded, {failed} failed.");

if (succeeded > 0 && results.Any(r => RestartHelper.IsRestartRequired(r.Result.Status == UpdateStatus.Succeeded
? RestartMode.Prompt : RestartMode.None)))
{
Console.WriteLine("Some drivers may require a restart.");
var userAccepted = RestartHelper.PromptUserForRestart("Driver update completed. Restart now?");
if (userAccepted)
await RestartHelper.RestartSystemAsync();
}

6. 全局配置

平台差异速查

平台驱动格式安装命令签名验证权限要求
Windows.infpnputil.exe /add-driver /installAuthenticode管理员
Linux.ko / .deb / .rpminsmod/modprobe / dpkg -i / rpm -ivhGPG(.sig/.ascroot/sudo
macOS.kext / .dext / .pkgkextload / SystemExtensions / installercodesign -vroot(SIP 和用户批准策略影响)

日志配置

// 性能敏感场景关闭日志
GeneralTracer.SetTracingEnabled(false);

// 排查问题时重新开启
GeneralTracer.SetTracingEnabled(true);

相关资源