推荐C#开发桌面自动更新程序(服务端与客户端)(3)
从刚才的建立的数据库中生成模型: 在Web.Config的appSettings节点中新增两个节点,用以设置更新程序的主文件名及更新包下载地址: appSettings add key = "主程
从刚才的建立的数据库中生成模型:
在Web.Config的appSettings节点中新增两个节点,用以设置更新程序的主文件名及更新包下载地址:
<appSettings> <add key="主程序文件名" value="MyApp.exe"/> <add key="更新包下载地址" value="Download.ashx"/> </appSettings>
引入一个GZip类用以打包(该类的源码将在文章末尾随本文示例源代码一并提供):
添加一个新的Web服务,名为Update.asmx:
书写如下代码:
[WebMethod] public string GetUpdate(string ClientVerison) { if (获取最新版本() != ClientVerison) { return System.Web.Configuration.WebConfigurationManager.AppSettings["更新包下载地址"]; } return null; } static string 获取最新版本() { string v = 获取文件版本(HttpContext.Current.Server.MapPath(string.Format("~/App_Data/Update/{0}", System.Web.Configuration.WebConfigurationManager.AppSettings["主程序文件名"]))); using (var c = new DatabaseEntities()) { //从数据库取得最新版本信息 var q = c.UpdateVersion.OrderByDescending(f => f.PublicTime).FirstOrDefault(); if (q == null || v != q.Version) { //数据库中的版本与当前主程序版本不一致时,以主程序版本为准,写入数据库,并生成新的更新文件包 var d = new UpdateVersion() { Version = v, PublicTime = DateTime.Now }; c.AddToUpdateVersion(d); c.SaveChanges(); 打包更新文件(HttpContext.Current.Server.MapPath("~/App_Data/Update/"), HttpContext.Current.Server.MapPath("~/App_Data/Update.gzip")); } } return v; } public static void 打包更新文件(string 打包目录, string 输出文件) { GZip.压缩(输出文件, Directory.GetFiles(打包目录).Concat(Directory.GetDirectories(打包目录)).ToArray()); } public static string 获取文件版本(string 文件路径) { FileVersionInfo f = FileVersionInfo.GetVersionInfo(文件路径); return f.FileVersion; }
创建Download.ashx,用以输出更新文件包:
代码:
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/zip"; context.Response.WriteFile(context.Server.MapPath("~/App_Data/Update.gzip")); }
服务端至此就编写完毕了。
精彩图集
精彩文章