old_flsystem/类库/OnlineRepair/Client.cs

373 lines
13 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using OnlineRepair;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
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
{
static string Path = System.IO.Directory.GetCurrentDirectory();
static string XMLPath = string.Empty;
static Client()
{
XMLPath = Path + "\\VersionUpdate.xml";
if (!File.Exists(XMLPath))
{
var old_path = Path + "\\LevelUpdate.xml";
if (!File.Exists(old_path)) throw new Exception("丢失【VersionUpdate.xml】更新包文件");
else
{
if (File.Exists(Path + "\\LevelUpdate.exe"))
{
try
{
File.Delete(Path + "\\LevelUpdate.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("找不到LevelUpdate.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;
}
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)
{
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;
}
}
}
#endregion XmlDocument读取
}
}