575 lines
23 KiB
C#
575 lines
23 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using System.Linq;
|
||
using System.Net;
|
||
using System.Text;
|
||
using System.Text.RegularExpressions;
|
||
using System.Web.Script.Serialization;
|
||
using System.Windows.Forms;
|
||
using System.Xml;
|
||
|
||
namespace VersionUpdate
|
||
{
|
||
public class UpdateClass
|
||
{
|
||
public string Name { get; set; }
|
||
public string Url { get; set; }
|
||
public string Version { get; set; }
|
||
public List<string> Message { get; set; }
|
||
}
|
||
public class Client
|
||
{
|
||
public delegate void DownLoadSuccessDelegate(List<UpdateClass> updateList);
|
||
|
||
/// <summary>
|
||
/// 更新用户信息事件
|
||
/// </summary>
|
||
public static DownLoadSuccessDelegate DownLoadSuccessEvent;
|
||
|
||
public static void OnDownLoadSuccessEvent(List<UpdateClass> updateList)
|
||
{
|
||
if (DownLoadSuccessEvent != null)
|
||
{
|
||
DownLoadSuccessEvent?.Invoke(updateList);
|
||
}
|
||
}
|
||
|
||
|
||
static string Path = System.IO.Directory.GetCurrentDirectory();
|
||
static string XMLPath = string.Empty;
|
||
|
||
static Client()
|
||
{
|
||
//VersionUpdate
|
||
//OnlineUpdate
|
||
//LevelUpdate
|
||
XMLPath = Path + "\\VersionUpdate.xml";
|
||
if (!File.Exists(XMLPath))
|
||
{
|
||
var old_path = Path + "\\OnlineUpdate.xml";
|
||
if (!File.Exists(old_path)) throw new Exception("丢失【VersionUpdate.xml】更新包文件!");
|
||
else
|
||
{
|
||
if (File.Exists(Path + "\\OnlineUpdate.exe"))
|
||
{
|
||
try
|
||
{
|
||
File.Delete(Path + "\\OnlineUpdate.exe");
|
||
}
|
||
catch (Exception)
|
||
{
|
||
}
|
||
}
|
||
File.Move(old_path, XMLPath);
|
||
}
|
||
}
|
||
}
|
||
#region XmlDocument读取
|
||
|
||
//public List<UpdateClass> GetVersions()
|
||
//{
|
||
// List<UpdateClass> msgs = new List<UpdateClass>();
|
||
// XmlDocument XmlDoc = new XmlDocument();
|
||
|
||
// if (!File.Exists(XMLPath)) throw new Exception("找不到VersionUpdate.xml必备文件!");
|
||
// //使用的时候,首先声明一个XmlDocument对象,然后调用Load方法,从指定的路径加载XML文件.
|
||
|
||
// XmlReaderSettings settings = new XmlReaderSettings();
|
||
// settings.IgnoreComments = true;//忽略文档里面的注释
|
||
// using (XmlReader reader = XmlReader.Create(XMLPath, settings))
|
||
// {
|
||
// XmlDoc.Load(reader);
|
||
// XmlNode xn = XmlDoc.SelectSingleNode("Files");
|
||
// // 得到根节点的所有子节点
|
||
// XmlNodeList xnl = xn.ChildNodes;
|
||
// foreach (XmlNode node in xnl)
|
||
// {
|
||
// try
|
||
// {
|
||
// //更新文件的别名
|
||
// var Name = node.Attributes["Name"].Value;
|
||
// //之前的配置文件地址
|
||
// var Url = node.Attributes["Url"].Value;
|
||
// var zipNameReg = Regex.Match(Url, @"([^/]+).xml");
|
||
// //文件名称
|
||
// var zipName = string.Empty;
|
||
// if (zipNameReg.Success)
|
||
// zipName = zipNameReg.Groups[1].Value;
|
||
// //版本号
|
||
// var CurVersion = Version.Parse(node.Attributes["Version"].Value);
|
||
|
||
// //XmlDocument temp_xml = new XmlDocument();
|
||
// //temp_xml.Load(Url);
|
||
// //var temp_node = temp_xml.SelectSingleNode("History");
|
||
|
||
// //var temp_datas = temp_node.SelectNodes("Data");
|
||
// ////更新内容
|
||
// //List<XmlNode> temp_update = new List<XmlNode>();
|
||
// //foreach (XmlNode item in temp_datas)
|
||
// //{
|
||
// // var ver = Version.Parse(item.Attributes["Ver"].Value);
|
||
// // if (ver > CurVersion)
|
||
// // {
|
||
// // //发现有更新
|
||
// // temp_update.Add(item);
|
||
// // }
|
||
// //}
|
||
|
||
// var result = HttpPost(zipName, "");
|
||
|
||
// //解析web返回的json消息
|
||
// //{"code":0,"data":{"Id":23,"key":23,"Active":true,"SoftName":"MainUpdate","Version":"2021.02.26.2","VersionLong":2021000200260002,"DownUrl":"http://fr-1303123972.cos.ap-chengdu.myqcloud.com/504e4621-0134-621d-b810-d30c0e41abca.zip","Message":"4444444555555666666666666","CreteTime":"\/Date(1614312406000)\/","CreateStr":"2021-02-26 12:06:46"}}
|
||
// if (!string.IsNullOrWhiteSpace(result))
|
||
// {
|
||
// var ver = string.Empty;
|
||
// var downUrl = string.Empty;
|
||
// var updateMesss = new List<string>();
|
||
// JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
|
||
// var dicResult = javaScriptSerializer.Deserialize<Dictionary<string, Object>>(result);
|
||
// if (dicResult != null)
|
||
// {
|
||
// if (dicResult["code"].ToString() != "0") throw new Exception("连接服务器失败,请稍后重试!");
|
||
// var data = dicResult["data"] as Dictionary<string, object>;
|
||
// if (data != null)
|
||
// {
|
||
// if ((bool)data["Active"])
|
||
// {
|
||
// if (string.IsNullOrWhiteSpace(ver))
|
||
// ver = data["Version"].ToString();
|
||
// if (string.IsNullOrWhiteSpace(downUrl))
|
||
// downUrl = data["DownUrl"].ToString();
|
||
|
||
// var temps = data["Message"].ToString().Split(new string[] { "[br]" }, StringSplitOptions.None);
|
||
// foreach (var temp in temps) updateMesss.Add(temp);
|
||
// }
|
||
|
||
// var MSG = new UpdateClass() { Name = Name, Url = downUrl, Message = updateMesss, Version = ver };
|
||
// msgs.Add(MSG);
|
||
|
||
// }
|
||
// }
|
||
// }
|
||
|
||
// //if (temp_update.Count > 0)
|
||
// //{
|
||
// // var MSG = new UpdateClass() { Name = Name, Url = temp_update[0].Attributes["Url"].Value, Message = new List<string>(), Version = temp_update[0].Attributes["Ver"].Value };
|
||
// // msgs.Add(MSG);
|
||
// // foreach (var item in temp_update)
|
||
// // {
|
||
// // var temps = item.Attributes["Msg"].Value.Split(new string[] { "[br]" }, StringSplitOptions.None);
|
||
// // foreach (var temp in temps) MSG.Message.Add(temp);
|
||
// // }
|
||
// //}
|
||
|
||
// }
|
||
// catch (Exception)
|
||
// {
|
||
// }
|
||
// #region xxx
|
||
// //try
|
||
// //{
|
||
// // var Name = node.Attributes["Name"].Value;
|
||
// // var Url = node.Attributes["Url"].Value;
|
||
// // var CurVersion = Version.Parse(node.Attributes["Version"].Value);
|
||
|
||
// // XmlDocument temp_xml = new XmlDocument();
|
||
// // temp_xml.Load(Url);
|
||
// // var temp_node = temp_xml.SelectSingleNode("History");
|
||
|
||
// // var temp_datas = temp_node.SelectNodes("Data");
|
||
// // //更新内容
|
||
// // List<XmlNode> temp_update = new List<XmlNode>();
|
||
// // foreach (XmlNode item in temp_datas)
|
||
// // {
|
||
// // var ver = Version.Parse(item.Attributes["Ver"].Value);
|
||
// // if (ver > CurVersion)
|
||
// // {
|
||
// // //发现有更新
|
||
// // temp_update.Add(item);
|
||
// // }
|
||
// // }
|
||
// // if (temp_update.Count > 0)
|
||
// // {
|
||
// // var MSG = new UpdateClass() { Name = Name, Url = temp_update[0].Attributes["Url"].Value, Message = new List<string>(), Version = temp_update[0].Attributes["Ver"].Value };
|
||
// // msgs.Add(MSG);
|
||
// // foreach (var item in temp_update)
|
||
// // {
|
||
// // var temps = item.Attributes["Msg"].Value.Split(new string[] { "[br]" }, StringSplitOptions.None);
|
||
// // foreach (var temp in temps) MSG.Message.Add(temp);
|
||
// // }
|
||
// // }
|
||
|
||
// //}
|
||
// //catch (Exception)
|
||
// //{
|
||
// //}
|
||
// #endregion
|
||
// }
|
||
// }
|
||
// return msgs;
|
||
//}
|
||
|
||
public List<UpdateClass> GetVersions()
|
||
{
|
||
List<UpdateClass> msgs = new List<UpdateClass>();
|
||
XmlDocument XmlDoc = new XmlDocument();
|
||
|
||
if (!File.Exists(XMLPath)) throw new Exception("找不到VersionUpdate.xml必备文件!");
|
||
//使用的时候,首先声明一个XmlDocument对象,然后调用Load方法,从指定的路径加载XML文件.
|
||
|
||
XmlReaderSettings settings = new XmlReaderSettings();
|
||
settings.IgnoreComments = true;//忽略文档里面的注释
|
||
using (XmlReader reader = XmlReader.Create(XMLPath, settings))
|
||
{
|
||
XmlDoc.Load(reader);
|
||
XmlNode xn = XmlDoc.SelectSingleNode("Files");
|
||
// 得到根节点的所有子节点
|
||
XmlNodeList xnl = xn.ChildNodes;
|
||
foreach (XmlNode node in xnl)
|
||
{
|
||
try
|
||
{
|
||
var Name = node.Attributes["Name"].Value;
|
||
var Url = node.Attributes["Url"].Value;
|
||
var CurVersion = Version.Parse(node.Attributes["Version"].Value);
|
||
|
||
XmlDocument temp_xml = new XmlDocument();
|
||
temp_xml.Load(Url);
|
||
var temp_node = temp_xml.SelectSingleNode("History");
|
||
|
||
var temp_datas = temp_node.SelectNodes("Data");
|
||
//更新内容
|
||
List<XmlNode> temp_update = new List<XmlNode>();
|
||
foreach (XmlNode item in temp_datas)
|
||
{
|
||
var ver = Version.Parse(item.Attributes["Ver"].Value);
|
||
if (ver > CurVersion)
|
||
{
|
||
//发现有更新
|
||
temp_update.Add(item);
|
||
}
|
||
}
|
||
|
||
if (temp_update.Count > 0)
|
||
{
|
||
var MSG = new UpdateClass() { Name = Name, Url = temp_update[0].Attributes["Url"].Value, Message = new List<string>(), Version = temp_update[0].Attributes["Ver"].Value };
|
||
msgs.Add(MSG);
|
||
foreach (var item in temp_update)
|
||
{
|
||
var temps = item.Attributes["Msg"].Value.Split(new string[] { "[br]" }, StringSplitOptions.None);
|
||
foreach (var temp in temps) MSG.Message.Add(temp);
|
||
}
|
||
}
|
||
}
|
||
catch (Exception)
|
||
{
|
||
|
||
}
|
||
}
|
||
}
|
||
|
||
return msgs;
|
||
}
|
||
|
||
//private string HttpPost(string softname, string version)
|
||
//{
|
||
// string content = $"SoftName={softname}";
|
||
// string url = "http://106.52.154.242:82/soft/GetLast?{content}";
|
||
// try
|
||
// {
|
||
// //获取提交的字节
|
||
// byte[] bs = Encoding.UTF8.GetBytes(content);
|
||
// //设置提交的相关参数
|
||
// HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
|
||
// req.Method = "POST";
|
||
// req.ContentType = "application/x-www-form-urlencoded";
|
||
// req.ContentLength = bs.Length;
|
||
// //提交请求数据
|
||
// Stream reqStream = req.GetRequestStream();
|
||
// reqStream.Write(bs, 0, bs.Length);
|
||
// reqStream.Close();
|
||
// //接收返回的页面,必须的,不能省略
|
||
// WebResponse wr = req.GetResponse();
|
||
// System.IO.Stream respStream = wr.GetResponseStream();
|
||
// System.IO.StreamReader reader = new System.IO.StreamReader(respStream, System.Text.Encoding.GetEncoding("utf-8"));
|
||
// string t = reader.ReadToEnd();
|
||
// Console.WriteLine(t);
|
||
// wr.Close();
|
||
// return t;
|
||
// }
|
||
// catch (Exception ex)
|
||
// {
|
||
// System.Web.HttpContext.Current.Response.Write("异常在getPostRespone:" + ex.Source + ":" + ex.Message);
|
||
// }
|
||
// return string.Empty;
|
||
//}
|
||
|
||
|
||
|
||
|
||
public delegate void NeedRestupdate();
|
||
public static NeedRestupdate NeedRestupdateEvent;
|
||
|
||
|
||
|
||
internal void DownFile(List<UpdateClass> update_msg, ProgressBar prog, Label label)
|
||
{
|
||
int i = 1;
|
||
foreach (var item in update_msg)
|
||
{
|
||
label?.Invoke(new Action(delegate { label.Text = $"正在下载第{i}个文件的更新包...(共{update_msg.Count}个)"; }));
|
||
DownloadFile(item.Url, MapFile($"{item.Name}_{item.Version}.zip", "Cache\\VersionUpdate"), prog);
|
||
i++;
|
||
}
|
||
label?.Invoke(new Action(delegate { label.Text = $"下载完成,请重启安装!"; }));
|
||
NeedRestupdateEvent?.BeginInvoke(null, null);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 检查是否有需要安装的程序
|
||
/// </summary>
|
||
public bool CheckInstall()
|
||
{
|
||
var files = GetInstallFiles();
|
||
if (files.Count > 0)
|
||
{
|
||
new InstallFileForm(files, this).ShowDialog();
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
public static bool StartProcess(string filename, string param = null)
|
||
{
|
||
try
|
||
{
|
||
if (!File.Exists(filename))
|
||
return false;
|
||
|
||
try
|
||
{
|
||
if (!System.IO.File.Exists(filename))
|
||
return false;
|
||
|
||
if (param != null)
|
||
System.Diagnostics.Process.Start(filename, param);
|
||
else
|
||
System.Diagnostics.Process.Start(filename);
|
||
System.Threading.Thread.Sleep(100);
|
||
}
|
||
catch (Exception)
|
||
{
|
||
// MessageBox.Show("启动应用程序时出错!原因:" + ex.Message);
|
||
}
|
||
return false;
|
||
|
||
}
|
||
catch (Exception)
|
||
{
|
||
// MessageBox.Show("启动应用程序时出错!原因:" + ex.Message);
|
||
}
|
||
return false;
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// 检查是否有新版本
|
||
/// </summary>
|
||
public bool CheckVersion()
|
||
{
|
||
var ves = GetVersions();
|
||
if (ves.Count > 0)
|
||
{
|
||
var f = new DownloadForm(ves, this);
|
||
f.ShowDialog();
|
||
return f.IsOk;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
public bool DownloadFile(List<UpdateClass> updateList)
|
||
{
|
||
if (updateList.Count > 0)
|
||
{
|
||
var f = new DownloadForm(updateList, this);
|
||
f.ShowDialog();
|
||
return f.IsOk;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获得需要安装的文件
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public List<FileInfo> GetInstallFiles()
|
||
{
|
||
var path = MapPath("Cache\\VersionUpdate");
|
||
DirectoryInfo dir = new DirectoryInfo(path);
|
||
var zips = dir.GetFiles("*_*.zip", SearchOption.TopDirectoryOnly);
|
||
var files = new List<FileInfo>();
|
||
foreach (var item in zips)
|
||
{
|
||
var reg = Regex.Match(item.Name, "^(.*?)_(.*?)\\.zip$");
|
||
if (reg.Success)
|
||
{
|
||
try
|
||
{
|
||
var name = item.Name;
|
||
var version = Version.Parse(reg.Groups[2].Value);
|
||
files.Add(item);
|
||
}
|
||
catch (Exception)
|
||
{ }
|
||
}
|
||
}
|
||
|
||
return files;
|
||
}
|
||
public void StartInstall()
|
||
{
|
||
var name = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName;
|
||
if (name == "VersionUpdate.exe") return;
|
||
StartProcess("VersionUpdate.exe", name);
|
||
}
|
||
|
||
public void InstallFile(FileInfo file)
|
||
{
|
||
try
|
||
{
|
||
var data = file.Name.Split('_');
|
||
var reg = Regex.Match(file.Name, "^(.*?)_(.*?).zip$");
|
||
if (!reg.Success) return;
|
||
Version version = null;
|
||
if (!Version.TryParse(reg.Groups[2].Value, out version)) return;
|
||
var name = reg.Groups[1].Value;
|
||
|
||
ZipArchive.UnZip(file.FullName, Path);
|
||
XmlDocument XmlDoc = new XmlDocument();
|
||
XmlReaderSettings settings = new XmlReaderSettings();
|
||
settings.IgnoreComments = true;//忽略文档里面的注释
|
||
using (XmlReader reader = XmlReader.Create(XMLPath, settings))
|
||
{
|
||
XmlDoc.Load(reader);
|
||
foreach (XmlNode _temp in XmlDoc.SelectSingleNode("Files").ChildNodes)
|
||
{
|
||
if (name == _temp.Attributes["Name"].Value)
|
||
{
|
||
_temp.Attributes["Version"].Value = version.ToString();
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
XmlDoc.Save(XMLPath);
|
||
|
||
File.Delete(file.FullName);
|
||
|
||
}
|
||
catch (Exception ex)
|
||
{ }
|
||
}
|
||
|
||
public static string MapFile(string file, string path = "")
|
||
{
|
||
return System.IO.Path.Combine(MapPath(path, true), file);
|
||
}
|
||
public static string MapPath(string path = "", bool CreateDirectory = true)
|
||
{
|
||
try
|
||
{
|
||
if (string.IsNullOrWhiteSpace(path))
|
||
{
|
||
return System.Windows.Forms.Application.StartupPath.ToString() + "\\";
|
||
}
|
||
path = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath.ToString() + "\\", path);
|
||
if (!(!CreateDirectory || Directory.Exists(path)))
|
||
{
|
||
Directory.CreateDirectory(path);
|
||
}
|
||
}
|
||
catch (Exception)
|
||
{ }
|
||
return path;
|
||
}
|
||
|
||
public void DownloadFile(string URL, string filename, ProgressBar prog)
|
||
{
|
||
try
|
||
{
|
||
|
||
float percent = 0;
|
||
if (File.Exists(filename)) File.Delete(filename);
|
||
|
||
Stream st = null;
|
||
Stream so = null;
|
||
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;
|
||
prog.Invoke(new Action(delegate
|
||
{
|
||
prog.Value = 0;
|
||
prog.Maximum = (int)totalBytes;
|
||
}));
|
||
|
||
st = myrp.GetResponseStream();
|
||
so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
|
||
try
|
||
{
|
||
long totalDownloadedByte = 0;
|
||
byte[] by = new byte[1024];
|
||
int osize = st.Read(by, 0, (int)by.Length);
|
||
while (osize > 0)
|
||
{
|
||
|
||
totalDownloadedByte = osize + totalDownloadedByte;
|
||
Application.DoEvents();
|
||
so.Write(by, 0, osize);
|
||
|
||
prog.Invoke(new Action(delegate { prog.Value = (int)totalDownloadedByte; }));
|
||
osize = st.Read(by, 0, (int)by.Length);
|
||
percent = (float)totalDownloadedByte / (float)totalBytes * 100;
|
||
Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
if (so != null)
|
||
{
|
||
so.Close();
|
||
so.Dispose();
|
||
so = null;
|
||
}
|
||
if (st != null)
|
||
{
|
||
st.Close();
|
||
st.Dispose();
|
||
st = null;
|
||
}
|
||
throw ex;
|
||
}
|
||
finally
|
||
{
|
||
if (so != null)
|
||
{
|
||
so.Close();
|
||
so.Dispose();
|
||
so = null;
|
||
}
|
||
if (st != null)
|
||
{
|
||
st.Close();
|
||
st.Dispose();
|
||
st = null;
|
||
}
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
}
|
||
}
|
||
|
||
#endregion XmlDocument读取
|
||
}
|
||
}
|