using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.Mvc; using System.Xml; using DSWeb.SoftMng.DBUtility; namespace DSWeb.SoftMng.Controllers { public class UpdateController : Controller { public static double Version = 1.0; public ActionResult Index() { //判断版本文件是否存在 if (!System.IO.File.Exists(Server.MapPath("~/version.xml"))) CreateXmlFile("1.0"); Version = Convert.ToDouble(ReadFile("~/version.xml")); //当前版本 ViewData["Version"]= Version.ToString("f1"); return View(); } /// /// 检查更新 /// /// public JsonResult CheckUpdate() { var src = ConfigurationManager.AppSettings["UpdateUrl"]; var updateVer = (Version + 0.1).ToString("f1"); var filename = src + "/update_" + updateVer + ".zip"; var success = RemoteFileExists(filename); return Json(new {success, filename }); } /// /// 文本文件读取 /// /// public string Read(string path) { try { StringBuilder notes = new StringBuilder(); StreamReader sr = new StreamReader(path, Encoding.Default); string line; while ((line = sr.ReadLine()) != null) notes.Append(line + "
"); return notes.ToString(); } catch (Exception e) { return ""; } } /// /// 判断远程文件是否存在 /// /// /// public static bool RemoteFileExists(string fileUrl) { HttpWebRequest re = null; HttpWebResponse res = null; try { re = (HttpWebRequest) WebRequest.Create(fileUrl); res = (HttpWebResponse) re.GetResponse(); if (res.ContentLength != 0) return true; } catch (Exception ex) { return false; } finally { if (re != null) re.Abort(); //销毁关闭连接 if (res != null) res.Close(); //销毁关闭响应 } return false; } /// /// 创建XML文档 /// /// public void CreateXmlFile(string version) { XmlDocument xmlDoc = new XmlDocument(); //创建类型声明节点 XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", ""); xmlDoc.AppendChild(node); //创建根节点 XmlNode root = xmlDoc.CreateElement("root"); xmlDoc.AppendChild(root); CreateNode(xmlDoc, root, "updateuser", Session["SHOWNAME"].ToString()); CreateNode(xmlDoc, root, "updatetime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); CreateNode(xmlDoc, root, "updateversion", version); try { xmlDoc.Save(Server.MapPath("~/version.xml")); } catch (Exception ex) { //显示错误信息 Response.Write(""); } } /// /// 读取XML文件 /// /// private string ReadFile(string file) { XmlDocument xmldoc = new XmlDocument(); try { xmldoc.Load(Server.MapPath(file)); XmlNode node = xmldoc.GetElementsByTagName("updateversion")[0]; if (node != null) return node.InnerText; } catch (Exception ex) { //显示错误信息 Response.Write(""); } return "1.0"; } /// /// 创建节点 /// /// xml文档 /// 父节点 /// 节点名 /// 节点值 /// public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value) { XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null); node.InnerText = value; parentNode.AppendChild(node); } /// /// 下载更新并解压覆盖安装 /// /// public JsonResult DownUpzip(string path) { List str = new List(); try { //下载 DownloadFile(path); //删除原文件 //System.IO.File.Delete(Server.MapPath("~/sql/update.mdb"));//数据库 //System.IO.File.Delete(Server.MapPath("~/note/readme.txt"));//升级说明 //解压 using (ZipArchive archive = ZipFile.OpenRead(Server.MapPath("~/download/update.zip"))) { foreach (ZipArchiveEntry file in archive.Entries) //循环读取压缩包中的文件 { var fileUnzipFullName = Path.Combine(Server.MapPath("~/"), file.FullName); //合并俩个字符串路径 if (file.Name == "") { //Assuming Empty for Directory Directory.CreateDirectory(fileUnzipFullName); continue; } file.ExtractToFile(fileUnzipFullName,true); //解压文件 } } //System.IO.Compression.ZipFile.ExtractToDirectory(Server.MapPath("~/download/update.zip"), Server.MapPath("~/")); //更新sql语句 string basePath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "sql"); //查询最新版本号 var oldver = DbHelperSQL.GetObject("select max([版本号]) from t_sys_soft").ToString().Replace(".",""); var dataSet = DbHelperMdfSQL.Query(oldver, basePath); if (dataSet.Tables.Count > 0) { var rows = dataSet.Tables[0].Rows; for (int i = 0; i < rows.Count; i++) { var sql = rows[i]["执行"].ToString(); String[] sqlArr = Regex.Split(sql.Trim(), "\r\n\\s*go", RegexOptions.IgnoreCase); foreach (string strsql in sqlArr) { if (strsql.Trim().Length > 1 && strsql.Trim() != "\r\n") { try { DbHelperSQL.ExecuteSql(strsql); } catch (Exception e) { str.Add(e.Message + " --" + DateTime.Now + "\r\n"); } } } } var rows1 = dataSet.Tables[1].Rows; for (int i = 0; i < rows1.Count; i++) { var sql = rows1[i]["执行"].ToString(); String[] sqlArr = Regex.Split(sql.Trim(), "\r\n\\s*go", RegexOptions.IgnoreCase); foreach (string strsql in sqlArr) { if (strsql.Trim().Length > 1 && strsql.Trim() != "\r\n") { try { DbHelperSQL.ExecuteSql(strsql); } catch (Exception e) { str.Add(e.Message + " --" + DateTime.Now + "\r\n"); } } } } } //更新版本 Version = Version + 0.1; var updateVer = Version.ToString("f1"); CreateXmlFile(updateVer); //获取更新详情 var upgradeNotes = Read(Server.MapPath("~/note/readme.txt")); return Json(new {success = true,msg=str, appVersion = updateVer,notes = upgradeNotes }); } catch (Exception ex) { str.Add(ex.Message); return Json(new {success = false, msg = str, appVersion=Version.ToString("f1") }); } } public void DownloadFile(string fullFilePath) { try { string basePath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "download"); if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath); string extension = Path.GetExtension(fullFilePath); string fileName = "update" + extension; string saveFilePath = Path.Combine(basePath, fileName); using (WebClient webClient = new WebClient()) webClient.DownloadFile(fullFilePath, saveFilePath); } catch (Exception ex) { //显示错误信息 Response.Write(""); } } } }