using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Windows.Forms;
using System.Xml;
namespace UAS_AutoUpdate
{
public partial class CheckUpdateWindow : Form
{
public static bool Zipped = false;
string ConfigFile = "Config.xml";
string ServerConfigFile = "ServerConfig.xml";
public bool CloseWhenFinished = false;
public CheckUpdateWindow()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
}
private void CheckUpdateWindow_Load(object sender, EventArgs e)
{
//使用WebClient从指定位置下载文件,然后进行解压缩覆盖
try
{
FileInfo info = new FileInfo(ConfigFile);
if (info.Length == 0)
{
XmlDocument doc = new XmlDocument();
//创建类型声明节点
XmlNode node = doc.CreateXmlDeclaration("1.0", "utf-8", "");
doc.AppendChild(node);
//创建根节点
XmlElement xeRoot = doc.CreateElement("cacheInfo");
doc.AppendChild(xeRoot);
doc.Save(ConfigFile);
}
}
catch (Exception)
{
MessageBox.Show("配置文件丢失,程序无法自动升级");
Process p = Process.Start("UAS_MES_NEW.exe");
CloseWhenFinished = true;
Close();
return;
}
try
{
WebClient wc = new WebClient();
Console.WriteLine(GetCacheData(ConfigFile, "ServerConfigPath").ToString());
wc.Credentials= new NetworkCredential("vsftpd", "vsftpd");
wc.DownloadFile(new Uri(GetCacheData(ConfigFile, "ServerConfigPath").ToString()), ServerConfigFile);
//服务器获取的配置文件
Version ver1 = new Version(GetCacheData(ServerConfigFile, "Version").ToString());
//本地的配置文件
Version ver2 = new Version(GetCacheData(ConfigFile, "Version").ToString());
//进行版本的比较
if (ver1 > ver2)
{
Process[] pro = Process.GetProcessesByName("UAS_MES_NEW");
if (pro.Length > 0)
{
string CloseProcess = MessageBox.Show(this.ParentForm, "检测到程序仍在运行,是否关闭", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
if (CloseProcess == "Yes")
{
for (int i = 0; i < pro.Length; i++)
{
Process.GetProcessById(pro[i].Id).Kill();
}
}
else
{
CloseWhenFinished = true;
Close();
return;
}
}
wc.DownloadProgressChanged += Wc_DownloadProgressChanged;
wc.DownloadFileAsync(new Uri(GetCacheData(ConfigFile, "UpdatePath").ToString()), "UAS_MES.zip");
SetCacheData(ConfigFile, "Version", ver1.ToString());
}
else
{
Process p = Process.Start("UAS_MES_NEW.exe");
CloseWhenFinished = true;
Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
LogManager.DoLog(ex.Message.ToString());
Process p = Process.Start("UAS_MES_NEW.exe");
CloseWhenFinished = true;
Close();
}
}
public static void SetCacheData(string FileName, string ParamName, object Value)
{
try
{
//根据地址读取xml文件
XmlDocument doc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings { CheckCharacters = false };
//忽略文档里面的注释
settings.IgnoreComments = true;
XmlReader reader = XmlReader.Create(FileName, settings);
doc.Load(reader);
//先得到根节点
XmlNode rootNode = doc.SelectSingleNode("cacheInfo");
//再由根节点去找制定的节点
XmlNodeList nodeList = rootNode.ChildNodes;
bool flag = false;
foreach (XmlNode node in nodeList)
{
//找到了这个节点名字
if (node.Name == ParamName)
{
//就直接赋值
node.InnerText = Value.ToString();
flag = true;
}
}
//如果没有该节点,就创建节点保存结果
if (!flag)
{
//创建节点
XmlElement newNode = doc.CreateElement(ParamName);
XmlAttribute attr = doc.CreateAttribute("Type");
attr.InnerText = Value.GetType().ToString();
newNode.InnerText = Value.ToString();
newNode.SetAttributeNode(attr);
//讲新建的节点挂到根节点上
rootNode.AppendChild(newNode);
}
//关闭Reader
reader.Close();
doc.Save(FileName);
}
catch (Exception)
{
}
}
public static object GetCacheData(string FileName, string ParamName)
{
try
{
object o = null;
//根据地址读取xml文件
XmlDocument doc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings { CheckCharacters = false };
//忽略文档里面的注释
settings.IgnoreComments = true;
XmlReader reader = XmlReader.Create(FileName, settings);
doc.Load(reader);
//先得到根节点
XmlNode rootNode = doc.SelectSingleNode("cacheInfo");
//再由根节点去找制定的节点
XmlNodeList nodeList = rootNode.ChildNodes;
foreach (XmlNode node in nodeList)
{
//找到了这个节点名字
if (node.Name == ParamName)
{
//返回节点的内容
switch (((XmlElement)node).GetAttribute("Type"))
{
case "System.String":
o = node.InnerText;
break;
case "System.Int32":
o = int.Parse(node.InnerText);
break;
case "System.Boolean":
o = node.InnerText == "True" ? true : false;
break;
default:
break;
}
break;
}
}
//关闭reader
reader.Close();
if (o == null)
return "";
else
return o;
}
catch (Exception)
{
return "";
}
}
private void Wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Action act = () =>
{
Console.WriteLine(e.ProgressPercentage);
_progressbar.Value = e.ProgressPercentage;
_processrate.Text = e.ProgressPercentage + "%";
};
if (IsHandleCreated)
this.Invoke(act);
if (e.ProgressPercentage == 100)
{
try
{
if (!Zipped)
{
ZipHelper.UnZip(Application.StartupPath + @"\UAS_MES.zip", Application.StartupPath);
Process p = Process.Start("UAS_MES_NEW.exe");
CloseWhenFinished = true;
Close();
}
else
{
CloseWhenFinished = true;
Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
private void CheckUpdateWindow_FormClosing(object sender, FormClosingEventArgs e)
{
if (!CloseWhenFinished)
e.Cancel = true;
}
}
public class ZipHelper
{
///
/// 用于解压缩Zip文件
///
///
///
public static void UnZip(string ZipFilePath, string UnZipPath)
{
if (!File.Exists(ZipFilePath))
{
throw new FileNotFoundException(string.Format("未能找到文件 '{0}' ", ZipFilePath));
}
if (!Directory.Exists(UnZipPath))
{
Directory.CreateDirectory(UnZipPath);
}
using (var s = new ZipInputStream(File.OpenRead(ZipFilePath)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
if (theEntry.IsDirectory)
{
continue;
}
string directorName = Path.Combine(UnZipPath, Path.GetDirectoryName(theEntry.Name));
string fileName = Path.Combine(directorName, Path.GetFileName(theEntry.Name));
if (!Directory.Exists(directorName))
{
Directory.CreateDirectory(directorName);
}
if (!string.IsNullOrEmpty(fileName))
{
try
{
//防止文件正在使用中报错
using (FileStream streamWriter = File.Create(fileName))
{
int size = 4096;
byte[] data = new byte[size];
while (size > 0)
{
size = s.Read(data, 0, data.Length);
streamWriter.Write(data, 0, size);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
File.Delete(Application.StartupPath + @"\UAS_MES.zip");
CheckUpdateWindow.Zipped = true;
}
}
}
}