C#实现在线更新

前言

在线升级通常指在连接网络的情况下从服务器下载更新文件以确保软件等处于最新状态

效果

在这里插入图片描述

流程图

在这里插入图片描述

主程序

下载

using System.Net;
using System.IO;
using System.IO.Compression;
using System.Threading;
using System.Diagnostics;

//从服务器下载系统安装包的方法
public void DownLoadFile()
{
	//更新文件的路径
    WebClient wc = new WebClient();

	//更新文件的路径,发布在服务器上
	string url = "http://192.168.22.148:8099/Fairy.zip";

	//获取应用应用的当前目录。
	string dir = System.IO.Directory.GetCurrentDirectory();

	//将字符串组合成一个路径加压缩包的名称
	string fileName = System.IO.Path.Combine(dir, "Fairy" + ".zip");

	//连接服务器的用户名和密码
	wc.Credentials = new System.Net.NetworkCredential("admin", "Radmin");

	//下载文件
	wc.DownloadFile(url, "Fairy.zip");
            
	//释放资源
	wc.Dispose();
}

窗体加载

//开启线程,实现正常运行的同时,下载也同时开始
private void Form1_Load(object sender, EventArgs e)
{
	//创建线程,下载方法
	Thread thread = new Thread(DownLoadFile);
	//开始线程
	thread.Start();
}

窗体关闭

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
	DialogResult result = MessageBox.Show("退出并更新", "提示", MessageBoxButtons.OKCancel,MessageBoxIcon.Information);
	if (result == DialogResult.OK)
	{
		//获取当前执行程序路径
		string dir = Directory.GetCurrentDirectory();
		
		//关闭自己,开启update更新程序
		Process unZip;
		unZip = Process.Start(dir + "\\update" + ".exe");

		System.Environment.Exit(0);
	}
	else
	{
		System.Environment.Exit(0);
	}
}

更新程序

解压

using System.Net;
using System.IO;
using System.IO.Compression;
using System.Threading;
using System.Diagnostics;

//将从服务器下载的安装包进行解压
 public bool Replace()
{
	//文件名
	string fileName = "Fairy";

	// GetCurrentDirectory
	// 获取应用程序的当前工作目录
	string dir = Directory.GetCurrentDirectory();
	//压缩包的路径
	string zipfile = Path.Combine(dir, fileName + ".zip");
	//当前工作目录中新建临时文件NewVersion存放新版本文件
	string extractPath = Path.Combine(dir, "verson");
	//解压缩文件到NewVersion中
	ZipFile.ExtractToDirectory(zipfile, extractPath);

	//遍历所有解压出来的文件
	foreach (string item in Directory.GetFiles(extractPath))
	{
		//把文件更新到程序运行路径
		File.Copy(item, System.IO.Path.Combine(dir, System.IO.Path.GetFileName(item)), true);
	}
	//删除压缩包
	File.Delete(zipfile);
	DirectoryInfo di = new DirectoryInfo((extractPath));
	//删除临时文件夹
	di.Delete(true);
	return true;
}

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 22
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 22
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值