1.程序启动时检查更新,如果可以更新,则判断是否为强制性更新,如果是则直接强制更新,不是则不处理,转为到程序更新模块中手动处理,这是更新最基本的原理
//检查更新
private void CheckUpdate()
{
bool upgrade; //是否有更新
bool force;//是否为强制更新
string download_url;//下载链接
UpdateVersion uv = new UpdateVersion();
uv.FileUpdate(out upgrade, out force, out download_url);
if (upgrade)
{
if(force)
{
string saveurl = AppDomain.CurrentDomain.BaseDirectory + "temp";
var filename = System.IO.Path.GetFileName(download_url);
new UpdateVersion().DownloadFile(download_url , saveurl, filename);
Process.Start(AppDomain.CurrentDomain.BaseDirectory + "Update.exe",filename);
Environment.Exit(0);
}
}
}
上面为检查更新代码,下载新包后开启更新程序更新当前文件
更新程序中需要做的事情(如果更新包比较大操作耗时则需要处理优化)
1.查找程序主进程并干掉,因为有可能此时主进程还没有结束,这时候执行更新会因为程序文件占用导致更新失败
private void killProcess()
{
Process[] pro = Process.GetProcesses();
for (int i = 0; i < pro.Length; i++)
{
if (pro[i].ProcessName.ToLower() == "xxx")
{
pro[i].Kill();
return;
}
}
}
2.解压更新包,解压完成后清理
private void Decompression()
{
var zip = cPath +"\\"+ _fileName;
SharpZip.UnpackFiles(zip, cPath+"\\");
if (File.Exists(zip))
File.Delete(zip);
}
3.更新文件
private void update()
{
System.Threading.Thread.Sleep(500);
CopyFile(cPath, path);
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "xxx.exe"))
{
Process.Start(AppDomain.CurrentDomain.BaseDirectory + "xxx.exe");
Environment.Exit(0);
}
}
private void CopyFile(string srcPath, string aimPath)
{
try
{
//判断需要复制的目录是否存在
if (!System.IO.Directory.Exists(srcPath))
return;
// 检查目标目录是否以目录分割字符结束如果不是则添加
if (aimPath[aimPath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
{
aimPath += System.IO.Path.DirectorySeparatorChar;
}
// 判断目标目录是否存在如果不存在则新建
if (!System.IO.Directory.Exists(aimPath))
return;
string[] fileList = System.IO.Directory.GetFileSystemEntries(srcPath);
// 遍历所有的文件和目录
foreach (string file in fileList)
{
// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
if (System.IO.Directory.Exists(file))
{
CopyFile(file, aimPath + System.IO.Path.GetFileName(file));
}
// 否则直接Copy文件
else
{
System.IO.File.Copy(file, aimPath + System.IO.Path.GetFileName(file), true);
}
}
}
catch (Exception e)
{
//更新失败
logs.ErrorLog(e.ToString());
Environment.Exit(0);
}
}