用C# 实现C/S模式下软件自动在线升级(3)

时间:2007-07-10 08:00 来源:网管之家bitsCN.com 字体:[ ]
  

 通过BatchDownload()函数来实现。升级程序检测旧的主程序是否活动,若活动则关闭旧的主程序;删除旧的主程序,拷贝临时文件夹中的文件到相应的位置;检查主程序的状态,若状态为活动的,则启动新的主程序。


private void BatchDownload(object data)
{
this.Invoke(this.activeStateChanger, new object[]{true, false});
try
{
DownloadInstructions instructions = (DownloadInstructions) data;
//批量下载
using(BatchDownloader bDL = new BatchDownloader())
{
bDL.CurrentProgressChanged += new DownloadProgressHandler(this.SingleProgressChanged);
bDL.StateChanged += new DownloadProgressHandler(this.StateChanged);
bDL.FileChanged += new DownloadProgressHandler(bDL_FileChanged);
bDL.TotalProgressChanged += new DownloadProgressHandler(bDL_TotalProgressChanged);
bDL.Download(instructions.URLs, instructions.Destination, (ManualResetEvent) this.cancelEvent);
}
}
catch(Exception ex)
{
   ShowErrorMessage(ex);
}
this.Invoke(this.activeStateChanger, new object[]{false, false});
this.labFileName.Text = "";
//更新程序
if(this._Update)
{
//关闭原有的应用程序
this.labDownFile.Text = "正在关闭程序....";
System.Diagnostics.Process[]proc=System.Diagnostics.Process.GetProcessesByName("TIMS");
//关闭原有应用程序的所有进程
foreach(System.Diagnostics.Process pro in proc)
{
pro.Kill();
}
DirectoryInfo theFolder=new DirectoryInfo(Path.GetTempPath()+"JurassicUpdate");
if(theFolder.Exists)
{
foreach(FileInfo theFile in theFolder.GetFiles())
{
//如果临时文件夹下存在与应用程序所在目录下的文件同名的文件,则删除应用程序目录下的文件
if(File.Exists(Application.StartupPath + \\"+Path.GetFileName(theFile.FullName)))
File.Delete(Application.StartupPath + "\\"+Path.GetFileName(theFile.FullName));
//将临时文件夹的文件移到应用程序所在的目录下
File.Move(theFile.FullName,Application.StartupPath + \\"+Path.GetFileName(theFile.FullName));
}
}
//启动安装程序
this.labDownFile.Text = "正在启动程序....";
System.Diagnostics.Process.Start(Application.StartupPath + "\\" + "TIMS.exe");
this.Close();
}
}  
 
 这段程序是实现在线升级的关键代码,步骤有点复杂:首先用Invoke方法同步调用状态改变进程,然后调用动态链接库中批量下载(BatchDownloader.cs)类启动批量下载,接着判断原有的主应用程序有没有关闭,如果没关闭,则用Process.Kill()来关闭主程序。接下来,判断临时文件夹下(即下载升级程序所在的目录)是否存在与应用程序所在目录下的文件同名的文件,如果存在同名文件,则删除应用程序目录下的文件,然后将临时文件夹的文件移到应用程序所在的目录下。最后重新启动主应用程序。这样更新就完成了。  

参考文献

[1] 庞澜.8051单片机在线升级软件的方法.http://www.mcublog.com/more.asp?name=MCUBLOG&id=3111.中国电子工程师博客站  
[2] 在WinForm中使用Web Services来实现软件自动升级( Auto Update )(C#)。http://www.cnblogs.com/x369/articles/105656.html .博客园
[3] 可复用的自动升级系统实现 。http://www.cnblogs.com/cdo/archive/2005/09/06/231229.html.博客园
[4] 用VB6.0编写自我升级的程序。http://www.enet.com.cn/article/2004/0525/A20040525311583.shtml  
[5] .NET后台智能传输服务实现自动更新(上). http://www.itonline.gd.cn/news/detail.asp?news_id=4071.IT在线

顶一下(5) 踩一下(3)
最新图文 1 2 3 4 5
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 密码: 验证码: