winform自动更新
本示例共由三个项目组成:
UpdateSolution:更新程序,用于更新WinForm
UpdateWeb:webService,更新服务,用于远程连接更新,获取版本号与新文件下载地址
WinForm:主程序
UpdateSolution.ini :当前版本文件 (本地)
先创建服务
UpdateWeb 核心代码:
service:
<%@ WebService Language="C#" CodeBehind="~/App_Code/Service.cs" Class="Service" %>
serviceCode:
/// <summary> /// 获取版本号 /// </summary> /// <returns>更新版本号</returns> [WebMethod] public string GetVersion() { return ConfigurationManager.ConnectionStrings["version"].ConnectionString; } /// <summary> /// 获取下载地址 /// </summary> /// <returns>下载地址</returns> [WebMethod] public string GetUrl() { return ConfigurationManager.ConnectionStrings["url1"].ConnectionString + ConfigurationManager.ConnectionStrings["directory"].ConnectionString; } /// <summary> /// 获取下载zip压缩包 /// </summary> /// <returns>下载zip压缩包</returns> [WebMethod] public string[] GetZips() { string folder=HttpRuntime.AppDomainAppPath + ConfigurationManager.ConnectionStrings["directorys"].ConnectionString; string[] zips = Directory.GetFileSystemEntries(folder); for (int i = 0; i < zips.Length; i++) { zips[i] = Path.GetFileName(zips[i]); } return zips; }
三个方法
配置文件web.config:
<connectionStrings> <!--版本号--> //要更新成什么版本号 <add name="version" connectionString="1.0.0"/> <!--下载地址--> <add name="url1" connectionString="http://localhost:8080/"/> <!--下载目录,最好为一级目录免得麻烦--> <add name="directory" connectionString="UpdateFile/Update.zip"/> <add name="directorys" connectionString="UpdateFile/"/> </connectionStrings>
服务完成了
发布一下
配置IIS
更新程序开始:
先引用上面的服务
引用完成
我的更新程序页面
按钮点击事件:
UpdateServices.Service service = new UpdateSolution.UpdateServices.Service();//webservice服务 string str = System.Windows.Forms.Application.StartupPath; zips = service.GetZips(); string url = str + @"\" + zips[0]; string DownUrl = service.GetUrl(); bool flag = DownloadFile(DownUrl, url, this.progressBar1, label1); if (flag) { UnZip(url, str); System.IO.File.Delete(url); IniClass ini = new IniClass(Application.StartupPath + @"\UpdateSolution.ini"); string serviceVersion = service.GetVersion();//服务端版本 ini.IniWriteValue("UpdateSolution", "version", serviceVersion);//更新成功后将版本写入配置文件 } Application.Exit();//退出升级程序 Process.Start("WinForm.exe");//打开主程序Main.exe
上面用的的两个辅助方法
/// <summary> /// c#,.net 下载文件 /// </summary> /// <param name="URL">下载文件地址</param> /// /// <param name="Filename">下载后的存放地址</param> /// <param name="Prog">用于显示的进度条</param> /// public bool DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1) { float percent = 0; try { System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); long totalBytes = myrp.ContentLength; if (prog != null) { prog.Maximum = (int)totalBytes; } System.IO.Stream st = myrp.GetResponseStream(); System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create); long totalDownloadedByte = 0; byte[] by = new byte[1024]; int osize = st.Read(by, 0, (int)by.Length); while (osize > 0) { totalDownloadedByte = osize + totalDownloadedByte; so.Write(by, 0, osize); if (prog != null) { prog.Value = (int)totalDownloadedByte; } osize = st.Read(by, 0, (int)by.Length); percent = (float)totalDownloadedByte / (float)totalBytes * 100; label1.Text = "当前更新下载进度" + percent.ToString() + "%"; Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息 } so.Close(); st.Close(); return true; } catch (System.Exception) { return false; throw; } } /// <summary> /// 解压zip 文件 /// </summary> /// <param name="fileFromUnZip"></param> /// <param name="fileToUnZip"></param> public static void UnZip(string fileFromUnZip, string fileToUnZip) { ZipInputStream inputStream = new ZipInputStream(File.OpenRead(fileFromUnZip)); ZipEntry theEntry; while ((theEntry = inputStream.GetNextEntry()) != null) { fileToUnZip += "/"; string fileName = Path.GetFileName(theEntry.Name); string path = Path.GetDirectoryName(fileToUnZip) + "/"; // Directory.CreateDirectory(path);//生成解压目录 if (fileName != String.Empty) { FileStream streamWriter = File.Create(path + fileName);//解压文件到指定的目录 int size = 2048; byte[] data = new byte[2048]; while (true) { size = inputStream.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); } } inputStream.Close(); }
读取ini文件的类:
public class IniClass { public string iniPath; [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); /// <summary> /// 构造方法 /// </summary> /// <param name="IniPath">文件路径</param> public IniClass(string iniPath) { this.iniPath = iniPath; } /// <summary> /// 写入INI文件 /// </summary> /// <param name="Section">项目名称(如 [TypeName] )</param> /// <param name="Key">键</param> /// <param name="Value">值</param> public void IniWriteValue(string Section, string Key, string Value) { WritePrivateProfileString(Section, Key, Value, this.iniPath); } /// <summary> /// 读出INI文件 /// </summary> /// <param name="Section">项目名称(如 [TypeName] )</param> /// <param name="Key">键</param> public string IniReadValue(string Section, string Key) { StringBuilder temp = new StringBuilder(500); int i = GetPrivateProfileString(Section, Key, "", temp, 500, this.iniPath); return temp.ToString(); } /// <summary> /// 验证文件是否存在 /// </summary> /// <returns>布尔值</returns> public bool ExistIniFile() { return File.Exists(iniPath); } }
WinForm:核心代码
////检测更新 IniClass ini = new IniClass(Application.StartupPath + @"\UpdateSolution.ini"); UpdateServices.Service service = new UpdateServices.Service(); string clientVersion = ini.IniReadValue("UpdateSolution", "version");//客户端版本 try { string serviceVersion = service.GetVersion();//服务端版本 this.lblbanben.Text = "V" + clientVersion; if (clientVersion != serviceVersion) { DialogResult dialogResult = MessageBox.Show("有新版本,是否更新?", "升级", MessageBoxButtons.OKCancel, MessageBoxIcon.Information); if (dialogResult == DialogResult.OK) { Application.Exit(); Process.Start("UpdateSolution.exe"); } } } catch (Exception ex) { }
更新的时候只需要改变web,config中的内容,与发布地址中文件的内容
Demo地址:https://lanzous.com/id1bg0b