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/contentcso/93099.html

六、工程结构

AutoUpdateSystem/
├── Services/            # 业务逻辑层
│   ├── UpdateService.cs
│   └── DifferentialUpdater.cs
├── Clients/             # 客户端实现
│   └── AutoUpdater.cs
├── Models/              # 数据模型
│   └── UpdateInfo.cs
├── Utils/               # 工具类
│   ├── FileValidator.cs
│   └── FileDownloader.cs
└── Tests/               # 单元测试
    └── UpdateServiceTests.cs
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值