在 C# WPF 应用程序中添加自动更新功能
- 安装AutoUpdater.NET:打开你的WPF项目,然后使用NuGet包管理器来安装AutoUpdater.NET。
配置更新过程:
a. 在你的WPF应用程序中找到主窗体的代码文件。
b. 引入AutoUpdater.NET命名空间:using AutoUpdaterDotNET;c. 在主窗体的
Loaded事件中配置AutoUpdater:以下是在主窗体的
Loaded事件中启动自动更新的示例:/** * 配置 AutoUpdater.NET 检查更新参数 */ private async void MainWindow_Loaded(object sender, RoutedEventArgs e) { try { await Task.Delay(300); if (GlobalConfig.SoftwareVersionId <= 0) { return; } /** 设置图标,将 System.Drawing.Icon 对象转换为 System.Drawing.Bitmap 对象 */ AutoUpdater.UpdateFormSize = new System.Drawing.Size(800, 500); try { AutoUpdater.Icon = Properties.Resources.Icon.ToBitmap(); } catch { /** 资源缺失不致命,保持默认图标即可,不阻断更新检查 */ } /** 从配置文件读取更新URL */ string updateUrl = $"{GlobalConfig.ServerUrl}/api/client/update/xml/{GlobalConfig.SoftwareVersionId}"; AutoUpdater.Start(updateUrl); } catch { /** async void 顶层兜底:避免 AutoUpdater / 资源加载异常被 Dispatcher.UnhandledException 上抛终结进程 */ } }- 确保将URL替换为指向你的更新XML文件的真实URL。
服务器配置 XML 文件:
<?xml version="1.0" encoding="UTF-8"?> <item> <version>1.1.0.0</version> <url>https://update.codespool.com/VideoWatermark/AutoUpdaterTest.zip</url> <changelog>https://update.codespool.com/VideoWatermark/release.html</changelog> <mandatory>false</mandatory> </item>服务器配置 changelog文件:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>软件更新日志</title> <style> body { font-family: Arial, sans-serif; line-height: 1.6; padding: 20px; } h1 { text-align: center; } h2 { margin-top: 30px; } ul { margin-left: 20px; } </style> </head> <body> <h1>软件更新日志</h1> <h2>版本 1.0.0</h2> <ul> <li>新增功能:用户登录</li> <li>新增功能:创建和编辑个人资料</li> <li>新增功能:查看其他用户资料</li> <li>修复了一些已知的 bug</li> </ul> </body> </html>