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/contentcso/93099.html
六、工程结构
AutoUpdateSystem/
├── Services/ # 业务逻辑层
│ ├── UpdateService.cs
│ └── DifferentialUpdater.cs
├── Clients/ # 客户端实现
│ └── AutoUpdater.cs
├── Models/ # 数据模型
│ └── UpdateInfo.cs
├── Utils/ # 工具类
│ ├── FileValidator.cs
│ └── FileDownloader.cs
└── Tests/ # 单元测试
└── UpdateServiceTests.cs
1579

被折叠的 条评论
为什么被折叠?



