System.Runtime.Serialization
private void InitData()
{
string url = GetConfigValue("UpgradeUrl");
string localExe = GetConfigValue("UpgradeExe");//UpgradeExe
string lan = GetConfigValue("Language");//UpgradeExe
string path = System.IO.Path.Combine(System.Environment.CurrentDirectory, localExe);
string xml = GetHttpContent(url);
upgrade model = stringToObj(xml);
isChinese = (lan == "CN");
Title = isChinese ? "自动升级" : "Auto upgrade";
CurrentVersion = isChinese ? "当前版本:" : "Current version:";
LastVersion = isChinese ? "最新版本:" : "Last version:";
UpgradeDate = isChinese ? "更新日期:" : "Update date :";
UpgradeContent = isChinese ? "更新内容:" : "Upgrade Content:";
Progress = isChinese ? "进度:" : "Progress:";
Cancel = isChinese ? "取消" : "Cancel:";
TxtDown = isChinese ? "下载" : "DownLoad:";
ParseStr(xml);
if (File.Exists(path))
{
string version = GetExeVersion(path);
string[] strArray = version.Split('.');
string[] strArrayNew = model.newVersion.Value.Split('.');
if (strArrayNew.Length == 4 && strArray.Length == 4)
{
Version localVersion = new Version(version);
Version newVersion = new Version(model.newVersion.Value);
CurrVersion = version;
if (newVersion > localVersion)
{
}
else
{
Environment.Exit(ProcessCode.IsLatestVersion); //客户端已经是最新版本
}
}
else
{
Environment.Exit(ProcessCode.VersionError); //版本号不对
}
}
else
{
Environment.Exit(ProcessCode.ClientExeNotExist); //客户端Exe不存在
}
}
private string GetConfigValue(string key)
{
try
{
return ConfigurationManager.AppSettings[key];
}
catch (Exception)
{
return string.Empty;
}
}
private upgrade stringToObj(string xmlStr)
{
byte[] byteArray = System.Text.Encoding.Default.GetBytes(xmlStr);
MemoryStream stream = new MemoryStream(byteArray);
XmlSerializer xs = new XmlSerializer(typeof(upgrade));
upgrade model = xs.Deserialize(stream) as upgrade;
stream.Close();
if (model != null)
{
return model;
}
else
{
return null;
}
}
private string GetExeVersion(string exePath)
{
string ret = string.Empty;
FileVersionInfo file1 = System.Diagnostics.FileVersionInfo.GetVersionInfo(exePath);
//版本号显示为“主版本号.次版本号.内部版本号.专用部件号”。
string FileVersions = String.Format("{0}.{1}.{2}.{3}", file1.FileMajorPart, file1.FileMinorPart, file1.FileBuildPart, file1.FilePrivatePart);
return FileVersions;
}
private void OnDownLoad(object o)
{
string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(CurrUpGradeInfo.Url));
if (!downFinish)
{
DownloadFile(CurrUpGradeInfo.Url, fileName);
}
else
{
Process.Start(fileName);
OnCancel(null);
}
}
public void ParseStr(string result)
{
var mStream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(result));
var serializer = new DataContractJsonSerializer((typeof(UpGradeInfo)));
CurrUpGradeInfo = (UpGradeInfo)serializer.ReadObject(mStream);
NewVersion = CurrUpGradeInfo.NewVersion;
UpGradeDate = CurrUpGradeInfo.UpGradeDate;
ProMaxValue = 100;
ProValue = 0;
UpGradeCotent = CurrUpGradeInfo.UpGradeContent;
}
public string GetHttpContent(string Url)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Proxy = null;
request.KeepAlive = false;
request.Method = "GET";
request.ContentType = "application/json; charset=UTF-8";
request.AutomaticDecompression = DecompressionMethods.None;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(responseStream, Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
responseStream.Close();
if (response != null)
{
response.Close();
}
if (request != null) {
response.Close();
}
if (request != null)
{
request.Abort();
}
return retString;
}
catch (Exception ex)
{
TxtMsg = ex.Message;
Environment.Exit(ProcessCode.NetException); //网络异常
return string.Empty;
}
}
bool downFinish = false;
public void DownloadFile(string URL, string filename)
{
IsEnableDown = false;
TxtMsg = string.Empty;
ProVisual = Visibility.Visible;
Task.Factory.StartNew(() =>
{
float percent = 0;
try
{
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;
ProMaxValue = (int)totalBytes;
System.IO.Stream st = myrp.GetResponseStream();
System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
long totalDownloadedByte = 0;
byte[] by = new byte[1024];
int osize = st.Read(by, 0, (int)by.Length);
while (osize > 0)
{
totalDownloadedByte = osize + totalDownloadedByte;
so.Write(by, 0, osize);
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
ProValue = (int)totalDownloadedByte;
percent = (float)Math.Round((float)totalDownloadedByte / (float)totalBytes * 100, 2);
ProMsg = $"{percent}%";
if (percent >= 100)
{
if (isChinese)
{
ProMsg = "下载完成";
TxtDown = "安装";
}
else
{
ProMsg = "Download complete";
TxtDown = "Install ";
}
IsEnableDown = true;
downFinish = true;
}
});
osize = st.Read(by, 0, (int)by.Length);
}
so.Close();
st.Close();
}
catch (System.Exception ex)
{
IsEnableDown = true;
TxtMsg = ex.Message;
}
});
}
}
[DataContract]
public class UpGradeInfo
{
[DataMember(Order = 0)]
public string ServerVersion { get; set; }
[DataMember(Order = 1)]
public string NewVersion { get; set; }
[DataMember(Order = 2)]
public string Url { get; set; }
[DataMember(Order = 3)]
public string UpGradeDate { get; set; }
[DataMember(Order = 4)]
public string UpGradeContent { get; set; }
}
[Serializable]
public class upgrade
{
public ItemObj newVersion { get; set; }
public ItemObj serverVersion { get; set; }
public ItemObj url { get; set; }
public ItemObj upgradeDate { get; set; }
public ItemObj upgradeContent { get; set; }
public ItemObj upgradeContent_en { get; set; }
}
public class ItemObj
{
[XmlAttribute("Value")]
public string Value;
}
public class ProcessCode
{
public const int NetException = -100;
public const int IsLatestVersion = -200;
public const int ClientExeNotExist = -300;
public const int VersionError = -400;
}