using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using log4net; using log4net.Config; namespace update { class Program { public static string SmallBackUrl = string.Empty; public static string Version = string.Empty; public static string CurrentPath = string.Empty; public static string UpdateReleasePath = string.Empty; public static string FormalPath = string.Empty; public static string BackPath = string.Empty; //初始化日志 static protected ILog logger = LogManager.GetLogger(typeof(Program)); static void Main(string[] args) { InitConfig(); InitLog4Net(); UpdateVersion(); } /// /// 前端版本更新 /// static public void UpdateVersion() { try { //更新App.config中的版本号 var config = new ConfigUtils(); string filepath = SmallBackUrl + @"/update/update.xml"; //下载更新XML WebClient mywebclient = new WebClient(); string basepath = CurrentPath + "../"; string downloadPath = basepath + @"update.xml"; if (!Directory.Exists(CurrentPath + @"/temp/")) { Directory.CreateDirectory(CurrentPath + @"/temp/"); } mywebclient.DownloadFile(filepath, downloadPath); //解析更新XML,读取信息 XmlDocument xmlDoc = new XmlDocument(); string xmlString = ReadContext(downloadPath); xmlDoc.LoadXml(xmlString); var item = xmlDoc.SelectSingleNode("//updateVersion"); double version = Convert.ToDouble(item.InnerXml); string downloadUrl = item.Attributes["name"]?.InnerXml; string updatemode = item.Attributes["mode"]?.InnerXml;//更新模式,全量(full),补丁(patch) double nowVersion = Convert.ToDouble(Version); if (version == nowVersion) { WebClient mywebclient2 = new WebClient(); string filePath2 = SmallBackUrl + @"/update/" + downloadUrl; string localPath = CurrentPath + @"\update\" + downloadUrl; string downpath = CurrentPath + @"\update\"; if (!Directory.Exists(downpath)) Directory.CreateDirectory(downpath); UpdateReleasePath = basepath + @"temp/"; //下载更新包 mywebclient2.DownloadFile(filePath2, localPath); //解压更新包至指定路径 if (Directory.Exists(UpdateReleasePath)) { DeleteDir(UpdateReleasePath, 1); Directory.CreateDirectory(UpdateReleasePath); } ZipFile.ExtractToDirectory(localPath, UpdateReleasePath); string mainpropath = basepath + "MainPro"; DirectoryInfo di = new DirectoryInfo(mainpropath);//正式包路径 DirectoryInfo di2 = new DirectoryInfo(UpdateReleasePath);//更新包解压路径 Thread.Sleep(3000); if ("full".Equals(updatemode)) { DirectoryInfo diback = new DirectoryInfo(mainpropath + DateTime.Now.ToString("yyyyMMddHHmmss"));//正式包路径 MoveDirectory(di, diback, true); //复制子目录 } CopyDirectory(di2, di, true); //复制子目录 } config.SetKey("updateVersion", item.InnerXml); } catch (Exception ex) { logger.Warn("更新版本出错" + ex.Message + "|" + ex.StackTrace); } string fullName = CurrentPath + "..\\MainPro\\DemoUI.exe"; var processInfo = new ProcessStartInfo(fullName); processInfo.WindowStyle = ProcessWindowStyle.Hidden; processInfo.UseShellExecute = false; processInfo.WorkingDirectory = Path.GetDirectoryName(fullName); Process.Start(processInfo); logger.Debug("应用更新版本结束,启动主程序" + fullName); Environment.Exit(1); } /// /// 初始化配置文件 /// public static void InitConfig() { try { var config = new ConfigUtils(); DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory); SmallBackUrl = config.GetKey("HttpUrl");//后台地址 Version = config.GetKey("updateVersion");//版本号 CurrentPath = di.FullName;//当前路径 //UpdateReleasePath = di.FullName + "up";//更新包解压路径 } catch (Exception e) { throw e; } } public static bool SetConfig(string Key, string Value) { try { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); if (config.AppSettings.Settings[Key] != null) config.AppSettings.Settings[Key].Value = Value; else config.AppSettings.Settings.Add(Key, Value); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); return true; } catch { return false; } } private static void InitLog4Net() { var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"); XmlConfigurator.ConfigureAndWatch(logCfg); } private static string ReadContext(string path) { FileStream fs = new FileStream(path, FileMode.Open); StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8); string context = sr.ReadToEnd(); fs.Close(); sr.Close(); sr.Dispose(); fs.Dispose(); return context; } public static void DeleteDir(string srcPath, int isSelf = 0) { try { DirectoryInfo dir = new DirectoryInfo(srcPath); FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //返回目录中所有文件和子目录 foreach (FileSystemInfo i in fileinfo) { if (i is DirectoryInfo) //判断是否文件夹 { DirectoryInfo subdir = new DirectoryInfo(i.FullName); subdir.Delete(true); //删除子目录和文件 } else { //如果 使用了 streamreader 在删除前 必须先关闭流 ,否则无法删除 sr.close(); File.Delete(i.FullName); //删除指定文件 } } if (isSelf == 1) { dir.Delete(); } } catch (Exception e) { logger.Error(e.Message); } } /// /// 拷贝目录内容 /// /// 源目录 /// 目的目录 /// 是否拷贝子目录 public static void CopyDirectory(DirectoryInfo source, DirectoryInfo destination, bool copySubDirs) { if (!destination.Exists) { destination.Create(); //目标目录若不存在就创建 } FileInfo[] files = source.GetFiles(); foreach (FileInfo file in files) { file.CopyTo(Path.Combine(destination.FullName, file.Name), true); //复制目录中所有文件,替换相同文件 } if (copySubDirs) { DirectoryInfo[] dirs = source.GetDirectories(); foreach (DirectoryInfo dir in dirs) { string destinationDir = Path.Combine(destination.FullName, dir.Name); CopyDirectory(dir, new DirectoryInfo(destinationDir), copySubDirs); //复制子目录 } } } /// /// 拷贝目录内容,删除本身 /// /// 源目录 /// 目的目录 /// 是否拷贝子目录 public static void MoveDirectory(DirectoryInfo source, DirectoryInfo destination, bool copySubDirs) { if (!destination.Exists) { destination.Create(); //目标目录若不存在就创建 } FileInfo[] files = source.GetFiles(); foreach (FileInfo file in files) { file.CopyTo(Path.Combine(destination.FullName, file.Name), true); //复制目录中所有文件,替换相同文件 file.Delete(); } if (copySubDirs) { DirectoryInfo[] dirs = source.GetDirectories(); foreach (DirectoryInfo dir in dirs) { string destinationDir = Path.Combine(destination.FullName, dir.Name); MoveDirectory(dir, new DirectoryInfo(destinationDir), copySubDirs); //复制子目录 } if (source.GetDirectories().Length == 0) source.Delete(); } } } }