1、程序内定义一个版本常量,和服务端配置文件对比,如果版本号比较旧就升级;
2、下载最新exe文件到当前目录命名为 new.exe ;
3、程序运行时不可以修改,删除操作,但可以重命名操作,所以我们将当前程序重命名为 bak.exe ;
4、将new.exe重命名为当前程序原名 ;
5、重启程序 ;
实现关键代码如下:
|
1
2
3
4
5
6
7
8
9
10
11
|
//更新检测和下载部分代码省略…… string FileName = Process.GetCurrentProcess().MainModule.ModuleName; //获取当前程序名
System.IO.Directory.Move(Application.StartupPath + "/" + FileName, Application.StartupPath + "/old.exe"); //将当前程序命名为old.exe
System.IO.Directory.Move(Application.StartupPath + "/update.exe", Application.StartupPath + "/" + FileName); //将下载的最新程序命名为当前程序名
string strAppFileName = Process.GetCurrentProcess().MainModule.FileName; //获取当前程序的完整路径
Process myNewProcess = new Process();
myNewProcess.StartInfo.FileName = strAppFileName; //设置要启动的程序
myNewProcess.StartInfo.WorkingDirectory = Application.ExecutablePath; //设置工作目录
myNewProcess.Start(); //准备重启程序
Application.Exit(); //退出当前程序集
|
在Form_Load内加入如下代码
|
1
2
|
if (System.IO.File.Exists(Application.StartupPath + "/old.exe"))
System.IO.File.Delete(Application.StartupPath + "/old.exe");
|
到此程序更新自己基本完成!