WPF版本的自动更新程序.docx
- 文档编号:24368928
- 上传时间:2023-05-26
- 格式:DOCX
- 页数:13
- 大小:16.98KB
WPF版本的自动更新程序.docx
《WPF版本的自动更新程序.docx》由会员分享,可在线阅读,更多相关《WPF版本的自动更新程序.docx(13页珍藏版)》请在冰豆网上搜索。
WPF版本的自动更新程序
WPF版本的自动更新程序
最近,拿到的项目代码是用WPF写的。
C/S结构的东西更新起来不太方便。
于是,就决定做个自动更新程序吧。
软件本身是用VS2010写的WPF版本的,所以更新程序也就决定用WPF来做吧。
虽说,以前用WinForm做过,感觉应该是差不多。
可实际操作过程中间,还是碰到了一些不太一样的地方吧。
不过,原理都是一样一样滴。
这里,只是更新程序的代码,至于版本判断的方法,方式多多吧。
这里的更新程序,需要放在软件主程序同目录下,而且我把客户端的版本号放在了软件的配置文件中了。
在更新完成后会去修改里边的版本信息。
至于,zip包的解压,引用了ICSharpCode.SharpZipLib.dll,网上很多下载的。
App.xaml.cs代码
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Configuration;
usingSystem.Data;
usingSystem.Linq;
usingSystem.Windows;
namespaceAutoUpdate
{
///
///App.xaml的交互逻辑
///
publicpartialclassApp:
Application
{
//重写OnStartup,获得启动程序
protectedoverridevoid
OnStartup(StartupEventArgse)
{
if(e.Args!
=null&&e.Args.Count()>0)
{
this.Properties["startexe"]=e.Args[0];
this.Properties["version"]=e.Args[1];
}
base.OnStartup(e);
}
}
}
MainWindow.xaml.cs代码
usingSystem;
usingSystem.Collections.Generic;usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows;
usingSystem.Windows.Controls;usingSystem.Windows.Data;
usingSystem.Windows.Documents;usingSystem.Windows.Input;
usingSystem.Windows.Media;
usingSystem.Windows.Media.Imaging;usingSystem.Windows.Navigation;usingSystem.Windows.Shapes;
usingSystem.Net;
usingSystem.Configuration;
usingSystem.IO;
usingSystem.Diagnostics;
usingSystem.Xml;
usingICSharpCode.SharpZipLib.Zip;namespaceAutoUpdate
{
///
///MainWindow.xaml的交互逻辑
///
publicpartialclassMainWindow:
Window
{
//更新包地址
privatestringurl="";
//文件名字
privatestringfilename="";
//下载文件存放全路径
privatestringfilepath="";
//更新后打开的程序名
stringstartexe="";
//新版本号
stringversion="";
publicMainWindow()
{
InitializeComponent();
pgbUpdate.Maximum=3;
if
(Application.Current.Properties["startexe"]!
=null)
{
startexe=
Application.Current.Properties["startexe"].ToString().Trim();
}
if
(Application.Current.Properties["version"]!
=null)
{
version=
Application.Current.Properties["version"].ToString().Trim();
}
}
privatevoidWindow_Activated(objectsender,EventArgse)
{
pgbUpdate.Value++;
url=
ConfigurationSettings.AppSettings["Url"].Trim();
if(url!
="")
{
filename=
url.Substring(url.LastIndexOf("/")+1);
//下载文件存放在临时文件夹中
filepath=
Environment.GetEnvironmentVariable("TEMP")+@"/"+filename;
if(filename!
="")
{
try
{
KillExeProcess();
DownloadFile();
UnZipFile();
UpdateVersionInfo();
OpenUpdatedExe();
writeLog("更新成功!
");
}
catch(Exceptionex)
{
writeLog(ex.Message);
}
}
else
{
writeLog("更新失败:
下载的文件名为空!
");
return;
}
}
else
{
writeLog("更新失败:
未在App.config中指定需要下载的文件位置!
");
}
if(File.Exists(filepath))
{
File.Delete(filepath);
}
this.Close();
}
///
///杀掉正在运行的需要更新的程序
///
privatevoidKillExeProcess()
{
//后缀起始位置
intstartpos=-1;
try
if(startexe!
="")
{
if(startexe.EndsWith(".EXE"))
{
startpos=
startexe.IndexOf(".EXE");
}
elseif(startexe.EndsWith(".exe"))
{
startpos=
startexe.IndexOf(".exe");
}
foreach(Processpin
Process.GetProcessesByName(startexe.Remove(startpos)))
{
p.Kill();
}
}
}
catch(Exceptionex)
thrownewException("清杀原程序进程出错:
"+ex.Message);
}
}
privatevoidpgbUpdate_ValueChanged(objectsender,RoutedPropertyChangedEventArgs
e)
{
pgbUpdate.Dispatcher.Invoke(new
Action object>(pgbUpdate.SetValue), System.Windows.Threading.DispatcherPriority.Background,ProgressBar.ValueProperty,pgbUpdate.Value); } /// ///下载更新包 /// publicvoidDownloadFile() { pgbUpdate.Value++; WebClientclient=newWebClient(); try { Uriaddress=newUri(url); if(File.Exists(filepath)) { File.Delete(filepath); } client.DownloadFile(address,filepath); } catch(Exceptionex) { thrownewException("下载更新文件出错: "+ex.Message); } } privatevoidUpdateVersionInfo() { try { Configurationcfa= ConfigurationManager.OpenExeConfiguration(startexe); cfa.AppSettings.Settings["Version"].Value=version; cfa.Save(); } catch(Exceptionex) { thrownewException("更新版本信息出错: "+ex.Message); } } /// ///打开更新后的程序 /// privatevoidOpenUpdatedExe() { try { if (ConfigurationManager.AppSettings["StartAfterUpdate"] =="true"&&startexe! ="") { Processopenupdatedexe=newProcess(); openupdatedexe.StartInfo.FileName=startexe; openupdatedexe.Start(); } } catch(Exceptionex) { thrownewException("打开更新后程序出错: "+ex.Message); } } #region不好用 /// ///解压压缩包,格式必须是*.zip,否则不能解压 ///需要添加System32下的Shell32.dll ///不好用总是弹出来对话框 /// //privatevoidUnZip() //{ //try //{ //ShellClasssc=newShellClass(); //FolderSrcFolder= sc.NameSpace(filepath); //FolderDestFolder= sc.NameSpace(System.Environment.CurrentDirectory); //FolderItemsitems=SrcFolder.Items(); //DestFolder.CopyHere(items,16); //} //catch(Exceptionex) //{ //MessageBox.Show("解压缩更新包出错: "+ex.Message,"提示信息",MessageBoxButton.OK,MessageBoxImage.Error); //} //} #endregion #region解压zip /// ///解压压缩包,格式必须是*.zip,否则不能解压 /// /// privatevoidUnZipFile() { pgbUpdate.Value++; try { using(ZipInputStreamzis=newZipInputStream(File.OpenRead(filepath))) { ZipEntrytheEntry; while((theEntry= zis.GetNextEntry())! =null) { stringdirectoryName=System.IO.Path.GetDirectoryName(theEntry.Name); stringzipfilename= System.IO.Path.GetFileName(theEntry.Name); if(directoryName.Length>0&&! Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } if(zipfilename! =String.Empty) { using(FileStreamstreamWriter=File.Create(theEntry.Name)) { intsize=2048; byte[]data=newbyte[2048]; while(true) { size= zis.Read(data,0,data.Length); if(size>0) { streamWriter.Write(data,0,size); } else { break; } } } } } } } catch(Exceptionex) { thrownewException("解压缩更新包出错: "+ex.Message); } } #endregion privatevoidwriteLog(stringstr) { stringstrLog= DateTime.Now.ToString("yyyy-MM-ddHH: mm: ss")+"" +str+"/r/n"; StreamWritererrorlog=new StreamWriter(System.IO.Path.Combine(Environment.CurrentDirectory,@"log.txt"),true); errorlog.Write(strLog); errorlog.Flush(); errorlog.Close(); } } } 更新程序的App.config xmlversion="1.0"encoding="utf-8"? > --更新包下载地址,注意要是zip--> --更新完毕是否启动-->
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- WPF 版本 自动更新 程序