当前位置: 首页 > news >正文

C#实现的自动升级系统

C#实现的自动升级系统,包含服务端和客户端实现,支持版本检测、差分更新和静默安装功能:


一、服务端实现(ASP.NET Core Web API)

1. 版本检测接口

[ApiController]
[Route("api/[controller]")]
public class UpdateController : ControllerBase
{private readonly IUpdateService _updateService;public UpdateController(IUpdateService updateService){_updateService = updateService;}[HttpGet("check")]public IActionResult CheckUpdate(string currentVersion){var updateInfo = _updateService.GetUpdateInfo(currentVersion);return Ok(updateInfo);}[HttpGet("download")]public IActionResult DownloadUpdate(string version){var fileStream = _updateService.GetUpdatePackage(version);return File(fileStream, "application/octet-stream", $"Update_{version}.zip");}
}

2. 更新服务实现

public class UpdateService : IUpdateService
{private readonly IConfiguration _config;private readonly IDatabaseService _dbService;public UpdateService(IConfiguration config, IDatabaseService dbService){_config = config;_dbService = dbService;}public UpdateInfo GetUpdateInfo(string currentVersion){var latestVersion = _dbService.GetLatestVersion();return new UpdateInfo{CurrentVersion = currentVersion,LatestVersion = latestVersion,NeedUpdate = !string.IsNullOrEmpty(latestVersion) && new Version(currentVersion) < new Version(latestVersion),DownloadUrl = $"{_config["UpdateBaseUrl"]}/download?version={latestVersion}"};}public Stream GetUpdatePackage(string version){var packagePath = Path.Combine(_config["UpdatePath"], $"Update_{version}.zip");return File.OpenRead(packagePath);}
}

二、客户端实现(WinForm)

1. 自动更新核心类

public class AutoUpdater
{private readonly string _updateUrl = "http://update.example.com/api/update";private readonly string _localVersionFile = "version.txt";public event EventHandler<UpdateProgressEventArgs> ProgressChanged;public event EventHandler<UpdateCompletedEventArgs> Completed;public async Task CheckForUpdates(){try{var response = await HttpClient.GetAsync($"{_updateUrl}/check?currentVersion={GetCurrentVersion()}");var updateInfo = JsonSerializer.Deserialize<UpdateInfo>(await response.Content.ReadAsStringAsync());if (updateInfo.NeedUpdate){await DownloadUpdate(updateInfo.LatestVersion);await InstallUpdate();}}catch (Exception ex){MessageBox.Show($"更新检查失败: {ex.Message}");}}private async Task DownloadUpdate(string version){using var client = new WebClient();client.DownloadProgressChanged += (s, e) => ProgressChanged?.Invoke(this, new UpdateProgressEventArgs(e.ProgressPercentage));await client.DownloadFileTaskAsync($"{_updateUrl}/download?version={version}",Path.Combine(Application.StartupPath, $"Update_{version}.zip"));}private async Task InstallUpdate(){var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());Directory.CreateDirectory(tempDir);ZipFile.ExtractToDirectory(Path.Combine(Application.StartupPath, $"Update_{GetCurrentVersion()}.zip"),tempDir);// 执行静默安装Process.Start(new ProcessStartInfo{FileName = Path.Combine(tempDir, "setup.exe"),Arguments = "/SILENT",UseShellExecute = false,CreateNoWindow = true}).WaitForExit();File.WriteAllText(_localVersionFile, GetCurrentVersion());Completed?.Invoke(this, new UpdateCompletedEventArgs(true));}private string GetCurrentVersion(){return File.Exists(_localVersionFile) ? File.ReadAllText(_localVersionFile) : "0.0.0.0";}
}public class UpdateInfo
{public string CurrentVersion { get; set; }public string LatestVersion { get; set; }public bool NeedUpdate { get; set; }public string DownloadUrl { get; set; }
}public class UpdateProgressEventArgs : EventArgs
{public int ProgressPercentage { get; }public UpdateProgressEventArgs(int percentage) => ProgressPercentage = percentage;
}public class UpdateCompletedEventArgs : EventArgs
{public bool Success { get; }public UpdateCompletedEventArgs(bool success) => Success = success;
}

三. 关键功能实现

1. 差分更新(使用BSdiff算法)

public class DifferentialUpdater
{public byte[] GeneratePatch(byte[] oldData, byte[] newData){var patch = new Bsdiff();return patch.Generate(oldData, newData);}public byte[] ApplyPatch(byte[] oldData, byte[] patch){var patcher = new Bsdiff();return patcher.Apply(oldData, patch);}
}

2. 文件校验

public class FileValidator
{public bool VerifyChecksum(string filePath, string expectedHash){using var sha256 = SHA256.Create();using var stream = File.OpenRead(filePath);var hash = sha256.ComputeHash(stream);return BitConverter.ToString(hash).Replace("-", "") == expectedHash;}
}

四、部署方案

1. 服务端配置(appsettings.json)

{"UpdateBaseUrl": "https://update.example.com","UpdatePath": "C:\\UpdatePackages","Database": {"ConnectionString": "Server=localhost;Database=UpdateDB;Trusted_Connection=True;"}
}

2. 客户端配置(app.config)

<configuration><appSettings><add key="UpdateCheckInterval" value="86400"/> <!-- 24小时检查一次 --><add key="AutoInstall" value="true"/></appSettings>
</configuration>

五、使用示例

// 初始化更新器
var updater = new AutoUpdater();
updater.ProgressChanged += (s, e) => progressBar1.Value = e.ProgressPercentage;
updater.Completed += (s, e) => MessageBox.Show(e.Success ? "更新成功" : "更新失败");// 启动更新检查
await updater.CheckForUpdates();

参考代码 C#自动升级实例源码 www.youwenfan.com/contentcnp/93099.html

六、工程结构

AutoUpdateSystem/
├── Services/            # 业务逻辑层
│   ├── UpdateService.cs
│   └── DifferentialUpdater.cs
├── Clients/             # 客户端实现
│   └── AutoUpdater.cs
├── Models/              # 数据模型
│   └── UpdateInfo.cs
├── Utils/               # 工具类
│   ├── FileValidator.cs
│   └── FileDownloader.cs
└── Tests/               # 单元测试└── UpdateServiceTests.cs
http://www.jsqmd.com/news/199812/

相关文章:

  • 2026年 摩托车机车品牌权威推荐榜:性能驾驭与潮流设计口碑之选 - 品牌企业推荐师(官方)
  • 7-Zip下载安装详细教程:高压缩率、轻量高效的文件管理利器
  • Dify插件如何实现热加载?深入源码解析动态扩展机制
  • 2026年1月卖家精灵优惠折扣码新鲜出炉!亚马逊运营效率神器必入 - 麦麦唛
  • 省选集训 7 - 数学问题
  • 机器视觉:Vision Transformer——打破CNN垄断的视觉革命先锋
  • GLM-4.6V-Flash-WEB能否识别医疗处方图像内容?
  • P6787 「SWTR-6」Snow Mountain
  • Dify附件系统稳定性提升秘籍:精准识别ID存在性的底层逻辑
  • 静态变量static
  • zzLLM大模型训练Trick系列(一)之拒绝采样
  • image2csv终极指南:一键将图像表格转换为CSV文件
  • GLM-4.6V-Flash-WEB能否理解病理切片图像?
  • 告别图片切换烦恼:MulimgViewer如何让你的工作效率翻倍?
  • 2026年人体工学椅选购全解读:告别久坐负担,科学守护脊椎健康 - 品牌推荐排行榜
  • AhabAssistantLimbusCompany智能助手:3个技巧让游戏自动化更高效
  • dns一样 两校区访问网站失败原由排查
  • 高压共轨喷油嘴0 433 171 968柴油喷油嘴0 433 171 968
  • 面部替换技术深度解析:从原理到实战应用
  • GLM-4.6V-Flash-WEB在按需付费模式下的成本控制优势
  • 2025年PDF表格数据提取实战指南:Tabula从入门到精通
  • VutronMusic技术架构解析:构建跨平台音乐播放的专业解决方案
  • GLM-4.6V-Flash-WEB与语音合成技术结合生成音视频解说
  • Vue 3拖拽交互7大实战场景:从基础列表到复杂看板
  • Estedad多语言字体:从入门到精通的实战指南 [特殊字符]
  • GLM-4.6V-Flash-WEB在跨境电子商务中的多语言支持能力
  • Real-ESRGAN轻量化架构:6个残差块如何实现动漫图像4K超分辨率?
  • 百度网盘免登录下载工具:三步实现高速文件获取
  • DLC解锁工具完全手册:CreamInstaller终极操作指南
  • 2026年论文ai生成终极指南!写论文神器app+一键生成技术路线图+图表代码全覆盖! - 资讯焦点