private void FrmUpdate_Load(object sender, System.EventArgs e) { panel2.Visible = false; btnFinish.Visible = false; string localXmlFile = Application.StartupPath + "\\UpdateList.xml"; string serverXmlFile = string.Empty; try { //从本地读取更新配置文件信息 updaterXmlFiles = new XmlFiles(localXmlFile); } catch { MessageBox.Show("配置文件出错!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); return; } //获取服务器地址 updateUrl = updaterXmlFiles.GetNodeValue("//Url"); AppUpdater appUpdater = new AppUpdater(); appUpdater.UpdaterUrl = updateUrl + "/UpdateList.xml"; //与服务器连接,下载更新配置文件 try { tempUpdatePath = Environment.GetEnvironmentVariable("Temp") + "\\" + "_" + updaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value + "_" + "y" + "_" + "x" + "_" + "m" + "_" + "\\"; appUpdater.DownAutoUpdateFile(tempUpdatePath); } catch { MessageBox.Show("与服务器连接失败,操作超时!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); return; } //获取更新文件列表 Hashtable htUpdateFile = new Hashtable(); serverXmlFile = tempUpdatePath + "\\UpdateList.xml"; if (!File.Exists(serverXmlFile)) { return; } availableUpdate = appUpdater.CheckForUpdate(serverXmlFile, localXmlFile, out htUpdateFile); if (availableUpdate > 0) { for (int i = 0; i < htUpdateFile.Count; i++) { string [] fileArray = (string [])htUpdateFile[i]; lvUpdateList.Items.Add(new ListViewItem(fileArray)); } } // else // btnNext.Enabled = false; }
public int CheckForUpdate() { string text = Application.StartupPath + "\\UpdateList.xml"; int result; if (!File.Exists(text)) { result = -1; } else { XmlFiles xmlFiles = new XmlFiles(text); string text2 = Environment.GetEnvironmentVariable("Temp") + "\\_" + xmlFiles.FindNode("//Application").Attributes["applicationId"].Value + "_y_x_m_\\"; this.UpdaterUrl = xmlFiles.GetNodeValue("//Url") + "/UpdateList.xml"; this.DownAutoUpdateFile(text2); string text3 = text2 + "\\UpdateList.xml"; if (!File.Exists(text3)) { result = -1; } else { XmlFiles xmlFiles2 = new XmlFiles(text3); XmlFiles xmlFiles3 = new XmlFiles(text); XmlNodeList nodeList = xmlFiles2.GetNodeList("AutoUpdater/Files"); XmlNodeList nodeList2 = xmlFiles3.GetNodeList("AutoUpdater/Files"); int num = 0; for (int i = 0; i < nodeList.Count; i++) { string[] array = new string[3]; string text4 = nodeList.Item(i).Attributes["Name"].Value.Trim(); string text5 = nodeList.Item(i).Attributes["Ver"].Value.Trim(); ArrayList arrayList = new ArrayList(); for (int j = 0; j < nodeList2.Count; j++) { string value = nodeList2.Item(j).Attributes["Name"].Value.Trim(); string value2 = nodeList2.Item(j).Attributes["Ver"].Value.Trim(); arrayList.Add(value); arrayList.Add(value2); } int num2 = arrayList.IndexOf(text4); if (num2 == -1) { array[0] = text4; array[1] = text5; num++; } else if (num2 > -1 && text5.CompareTo(arrayList[num2 + 1].ToString()) > 0) { array[0] = text4; array[1] = text5; num++; } } result = num; } } return(result); }
private void CheckWrok() { string strXmlPath = Application.StartupPath + "\\UpdateList.xml", serverXmlFile = string.Empty; try { m_UpdaterXmlFiles = new XmlFiles(strXmlPath); } catch (Exception exc) { MessageBox.Show("读取配置文件出错!" + exc.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); } m_Url = m_UpdaterXmlFiles.GetNodeValue("//Url"); AppUpdater appUpdater = new AppUpdater(); appUpdater.UpdaterUrl = m_Url + "/UpdateList.xml"; try { m_TempPath = Environment.GetEnvironmentVariable("Temp") + "\\" + "_" + m_UpdaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value + "_" + "l" + "_" + "i" + "_" + "s" + "_"; appUpdater.DownAutoUpdateFile(m_TempPath); } catch (Exception exc) { MessageBox.Show("与服务器连接失败,操作超时!" + exc.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); } //获取更新文件列表 Hashtable htUpdateFile = new Hashtable(); serverXmlFile = m_TempPath + "\\UpdateList.xml"; if (!File.Exists(serverXmlFile)) { return; } m_UpdateCount = appUpdater.CheckForUpdate(serverXmlFile, strXmlPath, out htUpdateFile); if (m_UpdateCount > 0) { label1.Text = "以下是需要更新的文件列表:"; btnNext.Enabled = true; for (int i = 0; i < htUpdateFile.Count; i++) { string[] fileArray = (string[])htUpdateFile[i]; lvUpdateList.Items.Add(new ListViewItem(fileArray)); } } else { label1.Text = "未发现需要更新的文件!"; MessageBox.Show("当前为最新版本!"); this.Close(); Application.ExitThread(); Application.Exit(); } }
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) { string localXmlFile = Application.StartupPath + "\\UpdateList.xml"; string serverXmlFile = string.Empty; try { //从本地读取更新配置文件信息 updaterXmlFiles = new XmlFiles(localXmlFile); } catch (Exception ee) { MessageBox.Show("配置文件出错!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); return; } //获取服务器地址 updateUrl = updaterXmlFiles.GetNodeValue("//Url"); AppUpdater appUpdater = new AppUpdater(); appUpdater.UpdaterUrl = updateUrl + "/UpdateList.xml"; //与服务器连接,下载更新配置文件 try { tempUpdatePath = Environment.GetEnvironmentVariable("Temp") + "\\" + "_" + updaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value + "_" + "y" + "_" + "x" + "_" + "m" + "_" + "\\"; appUpdater.DownAutoUpdateFile(tempUpdatePath); } catch { MessageBox.Show("与服务器连接失败,操作超时!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); return; } //获取更新文件列表 htUpdateFile = new Hashtable(); serverXmlFile = tempUpdatePath + "\\UpdateList.xml"; if (!File.Exists(serverXmlFile)) { MessageBox.Show("更新地址错误"); Application.Exit(); return; } availableUpdate = appUpdater.CheckForUpdate(serverXmlFile, localXmlFile, out htUpdateFile); }
private void btnNext_Click(object sender, System.EventArgs e) { if (availableUpdate > 0) { bHaveUpdate = false; listFileName.Clear(); foreach (ListViewItem sub in lvUpdateList.Items) { listFileName.Add(sub.Text); } btnNext.Enabled = false; btnNext.Text = "更新中..."; pbDownFile.Value = 0; backgroundWorker1.RunWorkerAsync(); } else { mainAppExe = updaterXmlFiles.GetNodeValue("//EntryPoint"); btnFinish_Click(sender, e); //MessageBox.Show("没有可用的更新!","自动更新",MessageBoxButtons.OK,MessageBoxIcon.Information); //return; } }
//判断主应用程序是否正在运行 private bool IsMainAppRun() { string mainAppExe = updaterXmlFiles.GetNodeValue("//EntryPoint"); bool isRun = false; Process [] allProcess = Process.GetProcesses(); foreach (Process p in allProcess) { if (p.ProcessName.ToLower() + ".exe" == mainAppExe.ToLower()) { isRun = true; //break; } } return(isRun); }
public int CheckUpdate() { string localXmlFile = Application.StartupPath + "\\UpdateList.xml"; string serverXmlFile = string.Empty; try { //从本地读取更新配置文件信息 updaterXmlFiles = new XmlFiles(localXmlFile); } catch { //MessageBox.Show("配置文件出错!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return(-1); } //获取服务器地址 updateUrl = updaterXmlFiles.GetNodeValue("//Url"); AppUpdater appUpdater = new AppUpdater(); appUpdater.UpdaterUrl = updateUrl + "/UpdateList.xml"; //与服务器连接,下载更新配置文件 try { tempUpdatePath = Environment.GetEnvironmentVariable("Temp") + "\\" + "_" + updaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value + "_" + "y" + "_" + "x" + "_" + "m" + "_" + "\\"; appUpdater.DownAutoUpdateFile(tempUpdatePath); } catch { //MessageBox.Show("与服务器连接失败,操作超时!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return(-2); } //获取更新文件列表 Hashtable htUpdateFile = new Hashtable(); serverXmlFile = tempUpdatePath + "\\UpdateList.xml"; if (!File.Exists(serverXmlFile)) { return(-3); } availableUpdate = appUpdater.CheckForUpdate(serverXmlFile, localXmlFile, out htUpdateFile); return(availableUpdate); }
/// <summary> /// 删除本地临时文件,启动主程序 /// </summary> protected void StartMainApp() { try { if (Directory.Exists(_appUpdate.LocalFileDir)) { Directory.Delete(_appUpdate.LocalFileDir, true); } } catch { } //_appUpdate.StartMainAppExe(_appUpdate.LocalVersion.EntryPoint); try { XmlFiles xmllocalfile = new XmlFiles(_appUpdate.LocalUpdateFile); string entryPoint = xmllocalfile.GetNodeValue("//Application/EntryPoint"); _appUpdate.StartMainAppExe(entryPoint); } catch (Exception ex) { LogHelper.WriteException(ex); } }
private void FrmUpdate_Load(object sender, System.EventArgs e) { string currentDirectory = Environment.CurrentDirectory; if (!AppConst.GetConfig()) { MessageBox.Show("配置文件读取失败!请确定配置文件放在" + currentDirectory + "该目录下"); return; } panel2.Visible = false; btnFinish.Visible = false; string localXmlFile = currentDirectory + "\\UpdateList.xml"; string serverXmlFile = string.Empty; try { //从本地读取更新配置文件信息 updaterXmlFiles = new XmlFiles(localXmlFile); } catch { MessageBox.Show("配置文件出错!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); return; } //获取服务器地址 updateUrl = updaterXmlFiles.GetNodeValue("//Url"); AppUpdater appUpdater = new AppUpdater(); appUpdater.UpdaterUrl = updateUrl + "/UpdateList.xml" + url_postfix; //与服务器连接,下载更新配置文件 try { //临时更新文件目录 tempUpdatePath = currentDirectory + "\\" + AppConst.TempFilePath; appUpdater.DownAutoUpdateFile(tempUpdatePath); } catch { MessageBox.Show("与服务器连接失败,操作超时!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); return; } //获取更新文件列表 htUpdateFile = new Hashtable(); serverXmlFile = tempUpdatePath + "\\UpdateList.xml"; if (!File.Exists(serverXmlFile)) { return; } availableUpdate = appUpdater.CheckForUpdate(serverXmlFile, localXmlFile, out htUpdateFile); if (availableUpdate > 0) { for (int i = 0; i < htUpdateFile.Count; i++) { string [] fileArray = (string [])htUpdateFile[i]; lvUpdateList.Items.Add(new ListViewItem(fileArray)); } } }
//下载可更新的文件 private void DownUpdateFile() { mainAppExe = updaterXmlFiles.GetNodeValue("//EntryPoint"); Process [] allProcess = Process.GetProcesses(); foreach (Process p in allProcess) { if (p.ProcessName.ToLower() + ".exe" == mainAppExe.ToLower()) { for (int i = 0; i < p.Threads.Count; i++) { p.Threads[i].Dispose(); } p.Kill(); isRun = true; //break; } } WebClient wcClient = new WebClient(); for (int i = 0; i < this.lvUpdateList1.Items.Count; i++) { string UpdateFile = lvUpdateList1.Items[i].Text.Trim(); string updateFileUrl = updateUrl + lvUpdateList1.Items[i].Text.Trim(); long fileLength = 0; WebRequest webReq = WebRequest.Create(updateFileUrl); WebResponse webRes = webReq.GetResponse(); fileLength = webRes.ContentLength; label1.Text = "正在下载更新文件,请稍后..."; pbDownFile.Value = 0; pbDownFile.Maximum = (int)fileLength; try { Stream srm = webRes.GetResponseStream(); StreamReader srmReader = new StreamReader(srm); byte[] bufferbyte = new byte[fileLength]; int allByte = (int)bufferbyte.Length; int startByte = 0; while (fileLength > 0) { Application.DoEvents(); int downByte = srm.Read(bufferbyte, startByte, allByte); if (downByte == 0) { break; } ; startByte += downByte; allByte -= downByte; pbDownFile.Value += downByte; float part = (float)startByte / 1024; float total = (float)bufferbyte.Length / 1024; int percent = Convert.ToInt32((part / total) * 100); this.lvUpdateList.Items[i].SubItems[2].Text = percent.ToString() + "%"; } string tempPath = tempUpdatePath + UpdateFile; CreateDirtory(tempPath); FileStream fs = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write); fs.Write(bufferbyte, 0, bufferbyte.Length); srm.Close(); srmReader.Close(); fs.Close(); } catch (WebException ex) { MessageBox.Show("更新文件下载失败!" + ex.Message.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } InvalidateControl(); //this.Cursor = Cursors.Default; }
/// <summary> /// 获得服务端更新版本列表,及最新的版本信息,同时去除比本地版本旧的版本信息 /// 修改升级策略,升级最近的全量包和最新的版本。不进行增量升级 /// 当UpdateFlag为2时,说明是全量升级包,之前的增量版本可以不升级 /// </summary> /// <returns>返回更新列表</returns> protected List <Version> GetServerVersions(ref string msg) { try { msg = string.Empty; _newVersion = null; Version fullVersion = null;//全量升级包 XmlFiles xmlserverfile = new XmlFiles(ServerUpdateFileClone); string serverUrl = xmlserverfile.GetNodeValue("//Updater/Url"); string entryPoint = xmlserverfile.GetNodeValue("//Application/EntryPoint"); XmlNodeList fileNodes = xmlserverfile.GetChildNodeList("//Dir"); if (fileNodes == null || fileNodes.Count < 1) { msg = "没有发现版本信息!"; LogHelper.WriteLog("服务端升级文件中没有包含升级版本信息!"); return(null); } _newVersion = new Version(); List <Version> serverVersions = new List <Version>(); int versionid = -1;//记录最新的版本标记 foreach (XmlNode node in fileNodes) { string sysifuse = node.Attributes["sysifuse"].InnerText.Trim(); if (sysifuse != "1") { continue; } string updateflag = "0"; try { updateflag = node.Attributes["updateflag"].InnerText.Trim(); } catch { updateflag = "0"; } int id = 0; int.TryParse(node.Attributes["value"].InnerText, out id); Version version = new Version(); string versionstr = string.Empty; try { versionstr = node.Attributes["ver"].InnerText; } catch { } version.StrVersion = versionstr; version.Ifuse = sysifuse; version.ValueVersion = id; version.Updateflag = updateflag; //比较版本,获得最新版本 if (versionid < id) { versionid = id; _newVersion.StrVersion = version.StrVersion; _newVersion.ValueVersion = version.ValueVersion; _newVersion.Ifuse = version.Ifuse; _newVersion.Updateflag = version.Updateflag; _newVersion.ServerUrl = serverUrl; _newVersion.EntryPoint = entryPoint; } //比较版本,去除老版本 if (id <= LocalVersion.ValueVersion) { continue; } //当当前版本是全量升级包时,记录最新的全量包 modify 2014.11.7 if (updateflag.Equals("2")) { if (fullVersion == null) { fullVersion = version; } else if (fullVersion.ValueVersion < id) { fullVersion = version; } } serverVersions.Add(version); //当 服务端版本配置文件 中有 必须升级标记则强制升级 if (version.Updateflag == "1") { _forceUpdate = true; } } //serverVersions.Clear(); //修改 保存 全量包的版本信息 modify 2014.11.7 if (fullVersion != null && fullVersion.ValueVersion > LocalVersion.ValueVersion && fullVersion.ValueVersion != versionid) { serverVersions.Clear(); serverVersions.Add(fullVersion); } //修改 保存 最新的版本信息 modify 2014.4.8 //if (versionid > LocalVersion.ValueVersion ) //{ // serverVersions.Add(_newVersion); //} return(serverVersions); } catch (Exception ex) { msg = "获得服务端版本信息时发生错误:" + ex.Message; LogHelper.WriteException(ex); return(null); } }
private void DownUpdateFile() { bool needCopy = true; mainAppExe = updaterXmlFiles.GetNodeValue("//EntryPoint"); Process [] allProcess = Process.GetProcesses(); foreach (Process p in allProcess) { if (p.ProcessName.ToLower() + ".exe" == mainAppExe.ToLower()) { for (int i = 0; i < p.Threads.Count; i++) { p.Threads[i].Dispose(); } p.Kill(); isRun = true; //break; } } try { WebClient wcClient = new WebClient(); for (int i = 0; i < htUpdateFile.Count; i++) { string[] fileList = new string[3]; fileList = (string[])htUpdateFile[i]; string UpdateFile = fileList[0].ToString().Trim(); string updateFileUrl = updateUrl + UpdateFile; long fileLength = 0; WebRequest webReq = WebRequest.Create(updateFileUrl); WebResponse webRes = webReq.GetResponse(); fileLength = webRes.ContentLength; lbState.Text = "正在下载更新文件,请稍后..."; pbDownFile.Value = 0; pbDownFile.Maximum = (int)fileLength; Stream srm = webRes.GetResponseStream(); StreamReader srmReader = new StreamReader(srm); byte[] bufferbyte = new byte[fileLength]; int allByte = (int)bufferbyte.Length; int startByte = 0; while (fileLength > 0) { Application.DoEvents(); int downByte = srm.Read(bufferbyte, startByte, allByte); if (downByte == 0) { break; } ; startByte += downByte; allByte -= downByte; pbDownFile.Value += downByte; float part = (float)startByte / 1024; float total = (float)bufferbyte.Length / 1024; int percent = Convert.ToInt32((part / total) * 100); this.lvUpdateList.Items[i].SubItems[2].Text = percent.ToString() + "%"; } string tempPath = tempUpdatePath + UpdateFile; CreateDirtory(tempPath); FileStream fs = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write); fs.Write(bufferbyte, 0, bufferbyte.Length); srm.Close(); srmReader.Close(); fs.Close(); } } catch (Exception ex) { needCopy = false; //MessageBox.Show("更新文件下载失败!" + ex.Message.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); WriteLog(ex.Message.ToString()); } //copy到程序目录 if (needCopy) { for (int i = 0; i < htUpdateFile.Count; i++) { string[] fileList = new string[3]; fileList = (string[])htUpdateFile[i]; string sfile = tempUpdatePath + fileList[0].ToString().Trim(); string dfile = Application.StartupPath + "\\" + fileList[0].ToString().Trim(); File.Copy(sfile, dfile, true); } } MessageBox.Show("更新结束,请重新打开软件!"); this.Close(); Application.ExitThread(); Application.Exit(); }
private void update_Tick(object sender, EventArgs e) { timer.Stop(); timer.Dispose(); if (!IsConnectInternet()) { label1.Visible = true; label7.Text = "无法连接到互联网!"; MessageBox.Show(this, "无法连接到互联网,请检查网络!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string localXmlFile = Application.StartupPath + "\\UpdateList.xml"; string serverXmlFile = string.Empty; try { //从本地读取更新配置文件信息 updaterXmlFiles = new XmlFiles(localXmlFile); } catch { MessageBox.Show(this, "读取配置文件出错,请联系管理员!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); return; } //获取服务器地址 updateUrl = updaterXmlFiles.GetNodeValue("//Url"); AppUpdater appUpdater = new AppUpdater(); appUpdater.UpdaterUrl = updateUrl + "/UpdateList.xml"; //与服务器连接,下载更新配置文件 try { tempUpdatePath = Environment.GetEnvironmentVariable("Temp") + "\\" + "_" + updaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value + "_" + "y" + "_" + "x" + "_" + "m" + "_" + "\\"; appUpdater.DownAutoUpdateFile(tempUpdatePath); } catch { MessageBox.Show(this, "与服务器连接失败,请求超时!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); return; } //获取更新文件列表 Hashtable htUpdateFile = new Hashtable(); serverXmlFile = tempUpdatePath + "\\UpdateList.xml"; if (!File.Exists(serverXmlFile)) { label1.Visible = true; label7.Text = "当前版本已经是最新版本!"; label7.Visible = true; MessageBox.Show(this, "当前版本已经是最新版本!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); return; } availableUpdate = appUpdater.CheckForUpdate(serverXmlFile, localXmlFile, out htUpdateFile); if (availableUpdate > 0) { //获取更新内容说明 this.txt_updateNotes.Visible = true; this.panel_updateNotes.Visible = true; this.btn_showUpdateNotes.Enabled = true; this.btn_showUpdateNotes.Text = "查看更新列表(&S)"; string[] updateNotes = appUpdater.GetUpdateNotes(serverXmlFile); if (updateNotes != null) { foreach (string note in updateNotes) { this.txt_updateNotes.AppendText(note + "\r\n"); } } else { this.txt_updateNotes.AppendText("暂时没有版本更新说明!"); } for (int i = 0; i < htUpdateFile.Count; i++) { string[] fileArray = (string[])htUpdateFile[i]; lvUpdateList.Items.Add(new ListViewItem(fileArray)); } label1.Visible = true; label1.Text = "发现新版本"; lvUpdateList.Visible = true; lbState.Visible = true; pbDownFile.Visible = true; label7.Visible = false; btnNext.Enabled = true; } else { label1.Visible = true; label7.Text = "当前版本已经是最新版本!"; label7.Visible = true; MessageBox.Show(this, "当前版本已经是最新版本!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); } }
private void DownUpdateFile() { m_MainApp = m_UpdaterXmlFiles.GetNodeValue("//EntryPoint"); Process[] allProcess = Process.GetProcesses(); foreach (Process p in allProcess) { if (p.ProcessName.ToLower() + ".exe" == m_MainApp.ToLower()) { for (int i = 0; i < p.Threads.Count; i++) { p.Threads[i].Dispose(); } p.Kill(); m_IsRun = true; break; } } WebClient wcClient = new WebClient(); for (int i = 0; i < this.lvUpdateList.Items.Count; i++) { string UpdateFile = lvUpdateList.Items[i].Text.Trim(); string updateFileUrl = m_Url + "\\" + UpdateFile; string tempPath = m_TempPath + "\\" + UpdateFile; long fileLength = 0; float percent = 0; try { HttpWebRequest Myrq = (HttpWebRequest)System.Net.HttpWebRequest.Create(updateFileUrl); Myrq.Proxy = null; HttpWebResponse myrp = (HttpWebResponse)Myrq.GetResponse(); fileLength = myrp.ContentLength; pbDownFile.Maximum = Convert.ToInt32(fileLength); pbDownFile.Value = 0; Stream st = myrp.GetResponseStream(); Stream so = new FileStream(tempPath, FileMode.Create, FileAccess.ReadWrite); long totalDownloadedByte = 0; byte[] by = new byte[1024]; int osize = st.Read(by, 0, (int)by.Length); while (osize > 0) { totalDownloadedByte = osize + totalDownloadedByte; pbDownFile.Value = Convert.ToInt32(totalDownloadedByte); Application.DoEvents(); so.Write(by, 0, osize); osize = st.Read(by, 0, (int)by.Length); percent = (float)totalDownloadedByte / (float)fileLength * 100; this.lvUpdateList.Items[i].SubItems[2].Text = percent.ToString("0.00") + "%"; Application.DoEvents(); } so.Close(); st.Close(); if (myrp != null) { myrp.Close(); } if (Myrq != null) { Myrq.Abort(); } } catch (WebException ex) { MessageBox.Show("更新文件下载失败!" + ex.Message.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } this.Invoke(new dlgtWork(InvalidateControl)); }
private void btnFinish_Click(object sender, EventArgs e) { try { this.Cursor = Cursors.WaitCursor; string bakPath = string.Format(@"{0}\updatebak\{1}", Environment.CurrentDirectory, DateTime.Now.ToString("yyMMddHHmmss")); this.CopyFile(this.tempUpdatePath, Environment.CurrentDirectory, bakPath); Directory.Delete(this.tempUpdatePath, true); } catch (Exception exception) { MessageBox.Show(exception.Message.ToString()); } finally { this.Cursor = Cursors.Default; } string xmlFile = Environment.CurrentDirectory + @"\UpdateList.xml"; try { XmlFiles files = new XmlFiles(xmlFile); string nodeValue = files.GetNodeValue("//EntryPoint"); string str4 = files.GetNodeValue("//Location"); string str5 = string.Empty; try { str5 = files.GetNodeValue("//BeforeExecutes"); } catch { } foreach (string str6 in str5.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { if (System.IO.File.Exists(str6)) { Process.Start(str6); } else { string path = string.Format(@"{0}\{1}", Environment.CurrentDirectory, str6); if (System.IO.File.Exists(path)) { Process.Start(path); } else { MessageBox.Show("没有找到升级完成后要自动执行的程序:{0}", path); } } } if (!string.IsNullOrEmpty(nodeValue)) { if (!string.IsNullOrEmpty(str4)) { nodeValue = string.Format(@"{0}\{1}\{2}", Environment.CurrentDirectory, str4, nodeValue); } if (System.IO.File.Exists(nodeValue)) { Process.Start(nodeValue); } else { MessageBox.Show(string.Format("没找到要升级后需要执行的主程序:{0}", nodeValue)); } } } catch (Exception exception2) { MessageBox.Show("出错!" + exception2.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand); } finally { base.Close(); base.Dispose(); } }
public int CheckForUpdate(string temppath, string serverXmlFile, string localXmlFile, out List<string[]> updateFileList) { updateFileList = new List<string[]>(); if (!System.IO.File.Exists(localXmlFile) || !System.IO.File.Exists(serverXmlFile)) { return -1; } XmlFiles files = new XmlFiles(serverXmlFile); XmlFiles files2 = new XmlFiles(localXmlFile); XmlNodeList nodeList = files.GetNodeList("AutoUpdater/Components"); XmlNodeList list2 = files2.GetNodeList("AutoUpdater/Components"); Dictionary<string, XmlNode> dictionary = new Dictionary<string, XmlNode>(list2.Count); string[] commandLineArgs = Environment.GetCommandLineArgs(); if (((commandLineArgs == null) || (commandLineArgs.Length <= 1)) || (commandLineArgs[1].ToLower() != "true")) { for (int j = 0; j < list2.Count; j++) { dictionary.Add(list2.Item(j).Attributes["Name"].Value.Trim(), list2[j]); } } int num2 = 0; bool result = false; try { string nodeValue = files.GetNodeValue("//reset"); if (!string.IsNullOrEmpty(nodeValue)) { bool.TryParse(nodeValue, out result); } } catch { } Dictionary<string, bool> dictionary2 = new Dictionary<string, bool>(); for (int i = nodeList.Count - 1; i >= 0; i--) { XmlNode node = nodeList[i]; string componentName = node.Attributes["Name"].Value.Trim(); string updateUrl = node.Attributes["Url"].Value.Trim(); string path = this.DownAutoUpdateFile(temppath, componentName, updateUrl); string str5 = Path.Combine(Environment.CurrentDirectory, string.Format("{0}component.xml", componentName)); if (!System.IO.File.Exists(path)) { MessageBox.Show("找不到文件:" + path); } XmlNode node2 = null; if (!System.IO.File.Exists(str5)) { foreach (XmlNode node3 in list2) { if (node3.Attributes["Name"].Value.Trim() == componentName) { foreach (XmlNode node4 in node3.ChildNodes) { if (node4.Name == "Files") { node2 = node4; break; } } break; } } } else { XmlFiles files3 = new XmlFiles(str5); foreach (XmlNode node5 in files3.GetNodeList("Component")) { if (node5.Name == "Files") { node2 = node5; break; } } } XmlFiles files4 = new XmlFiles(path); foreach (XmlNode node6 in files4.GetNodeList("Component")) { if (!(node6.Name == "Files")) { continue; } bool flag2 = dictionary.ContainsKey(componentName); Dictionary<string, string> dictionary3 = new Dictionary<string, string>(); if (flag2 && (node2 != null)) { foreach (XmlNode node7 in node2.ChildNodes) { if (node7.Name == "File") { if (!dictionary3.ContainsKey(node7.Attributes["Name"].Value.Trim())) { dictionary3.Add(node7.Attributes["Name"].Value.Trim(), node7.Attributes["Ver"].Value.Trim()); } else { MessageBox.Show(string.Format("包含重复的升级项目文件:{0},系统将忽略!", node7.Attributes["Name"].Value.Trim())); } } } } foreach (XmlNode node8 in node6.ChildNodes) { if (!(node8.Name == "File")) { continue; } string[] item = new string[5]; string key = node8.Attributes["Name"].Value.Trim(); string str7 = node8.Attributes["Ver"].Value.Trim(); if (!dictionary3.ContainsKey(key) || (dictionary3.ContainsKey(key) && ((str7.CompareTo(dictionary3[key]) > 0) || (result && (str7.CompareTo(dictionary3[key]) < 0))))) { item[0] = key; item[1] = str7; item[3] = updateUrl; if (!dictionary3.ContainsKey(key) || (str7.CompareTo(dictionary3[key]) > 0)) { item[4] = key; } else { item[4] = key + str7; } if (!dictionary2.ContainsKey(key)) { updateFileList.Add(item); dictionary2.Add(key, true); } num2++; } } } } return num2; }
private void CheckWrok() { string strXmlPath = Application.StartupPath + "\\UpdateList.xml", serverXmlFile = string.Empty; try { m_UpdaterXmlFiles = new XmlFiles(strXmlPath); } catch (Exception exc) { MessageBox.Show("��ȡ�����ļ�����!" + exc.Message, "����", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); } m_Url = m_UpdaterXmlFiles.GetNodeValue("//Url"); AppUpdater appUpdater = new AppUpdater(); appUpdater.UpdaterUrl = m_Url + "/UpdateList.xml"; try { m_TempPath = Environment.GetEnvironmentVariable("Temp") + "\\" + "_" + m_UpdaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value + "_" + "l" + "_" + "i" + "_" + "s" + "_"; appUpdater.DownAutoUpdateFile(m_TempPath); } catch (Exception exc) { MessageBox.Show("�����������ʧ��,������ʱ!" + exc.Message, "��ʾ", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); } //��ȡ�����ļ��б� Hashtable htUpdateFile = new Hashtable(); serverXmlFile = m_TempPath + "\\UpdateList.xml"; if (!File.Exists(serverXmlFile)) return; m_UpdateCount = appUpdater.CheckForUpdate(serverXmlFile, strXmlPath, out htUpdateFile); if (m_UpdateCount > 0) { label1.Text = "��������Ҫ���µ��ļ��б��"; btnNext.Enabled = true; for (int i = 0; i < htUpdateFile.Count; i++) { string[] fileArray = (string[])htUpdateFile[i]; lvUpdateList.Items.Add(new ListViewItem(fileArray)); } } else { label1.Text = "δ������Ҫ���µ��ļ���"; MessageBox.Show("��ǰΪ���°汾��"); this.Close(); Application.ExitThread(); Application.Exit(); } }
private void FrmUpdate_Load(object sender, System.EventArgs e) { // if (!CheckInetConnection()) // { // MessageBox.Show("无网络连接!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); // this.Close(); // return; // } //foreach (Process my in System.Diagnostics.Process.GetProcesses()) //{ // if (my.ProcessName == "FairiesCoolerCash") // { // my.Kill(); // } //} panel2.Visible = false; btnFinish.Visible = false; string localXmlFile = Application.StartupPath + "\\UpdateList.xml"; string serverXmlFile = string.Empty; try { //从本地读取更新配置文件信息 updaterXmlFiles = new XmlFiles(localXmlFile ); } catch { MessageBox.Show("配置文件出错!","错误",MessageBoxButtons.OK,MessageBoxIcon.Error); this.Close(); return; } //获取服务器地址 updateUrl = updaterXmlFiles.GetNodeValue("//Url"); description = updaterXmlFiles.GetNodeValue("//Description"); this.Text = description; AppUpdater appUpdater = new AppUpdater(); appUpdater.UpdaterUrl = updateUrl + "/UpdateList.xml"; //与服务器连接,下载更新配置文件 try { tempUpdatePath = Application.StartupPath + "\\AutoUpdateFiles" + "\\" + "_" + updaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value + "_" + "y" + "_" + "x" + "_" + "m" + "_" + "\\"; appUpdater.DownAutoUpdateFile(tempUpdatePath); } catch { MessageBox.Show("与服务器连接失败,操作超时!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information); this.Close(); return; } //获取更新文件列表 Hashtable htUpdateFile = new Hashtable(); serverXmlFile = tempUpdatePath + "\\UpdateList.xml"; if(!File.Exists(serverXmlFile)) { return; } availableUpdate = appUpdater.CheckForUpdate(serverXmlFile,localXmlFile,out htUpdateFile); if (availableUpdate > 0) { for(int i=0;i<htUpdateFile.Count;i++) { string [] fileArray =(string []) htUpdateFile[i]; lvUpdateList.Items.Add(new ListViewItem(fileArray)); } } // else // btnNext.Enabled = false; }
private void FrmUpdate_Load(object sender, System.EventArgs e) { string localXmlFile = Application.StartupPath + "\\Version.xml"; string serverXmlFile = string.Empty; try { //从本地读取更新配置文件信息 updaterXmlFiles = new XmlFiles(localXmlFile); } catch { //MessageBox.Show("配置文件出错!","错误",MessageBoxButtons.OK,MessageBoxIcon.Error); WriteLog("配置文件出错"); this.Close(); return; } //获取服务器地址 updateUrl = updaterXmlFiles.GetNodeValue("//Url"); AppUpdater appUpdater = new AppUpdater(); appUpdater.UpdaterUrl = updateUrl + "Version.xml"; //WriteLog(appUpdater.UpdaterUrl); //与服务器连接,下载更新配置文件 try { tempUpdatePath = Environment.GetEnvironmentVariable("Temp") + "\\" + "_" + updaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value + "_" + "u" + "_" + "p" + "_" + "\\"; deleteDirectory(tempUpdatePath);//删除临时目录 appUpdater.DownAutoUpdateFile(tempUpdatePath); } catch { //MessageBox.Show("与服务器连接失败,操作超时!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information); WriteLog("与服务器连接失败,操作超时!"); this.Close(); return; } //获取更新文件列表 serverXmlFile = tempUpdatePath + "Version.xml"; if (!File.Exists(serverXmlFile)) { this.Close(); return; } availableUpdate = appUpdater.CheckForUpdate(serverXmlFile, localXmlFile, out htUpdateFile); if (availableUpdate > 0) { if (DialogResult.OK == MessageBox.Show("发现新版本! 要更新吗?", mainAppName, MessageBoxButtons.OKCancel, MessageBoxIcon.Question)) { for (int i = 0; i < htUpdateFile.Count; i++) { string[] fileArray = (string[])htUpdateFile[i]; lvUpdateList.Items.Add(new ListViewItem(fileArray)); } //this.btnNext_Click(sender, e); } else { this.Close();//do not need to open the window } } else { this.Close(); } }
private void DownUpdateFile() { //this.Cursor = Cursors.WaitCursor; this.SetFormCursor(Cursors.WaitCursor); //this.backgroundWorker1.RunWorkerAsync(); mainAppExe = updaterXmlFiles.GetNodeValue("//EntryPoint"); Process[] allProcess = Process.GetProcessesByName(mainAppExe.Split('.')[0]);//Process.GetProcesses(); foreach(Process p in allProcess) { //if (p.ProcessName.ToLower() + ".exe" == mainAppExe.ToLower() ) //{ for(int i=0;i<p.Threads.Count;i++) p.Threads[i].Dispose(); p.Kill(); isRun = true; //break; //} } WebClient wcClient = new WebClient(); try { for(int i = 0;i < this.lvUpdateList.Items.Count;i++) { string UpdateFile = GetText(i).Trim(); string updateFileUrl = updateUrl + UpdateFile; long fileLength = 0; WebRequest webReq = WebRequest.Create(updateFileUrl); WebResponse webRes = webReq.GetResponse(); fileLength = webRes.ContentLength; SetStateText("正在下载更新文件,请稍后..."); SetProgressValue(0); SetProgressMaximum((int)fileLength); Stream srm = webRes.GetResponseStream(); StreamReader srmReader = new StreamReader(srm); byte[] bufferbyte = new byte[fileLength]; int allByte = (int)bufferbyte.Length; int startByte = 0; while (fileLength > 0) { Application.DoEvents(); int downByte = srm.Read(bufferbyte, startByte, allByte); if (downByte == 0) { break; }; startByte += downByte; allByte -= downByte; AddProgressValue(downByte); float part = (float)startByte / 1024; float total = (float)bufferbyte.Length / 1024; int percent = Convert.ToInt32((part / total) * 100); SetSubText(i, percent.ToString() + "%"); } //解析网站路径一级目录结构 string strLocalPath = UpdateFile.Replace("/", "\\"); string tempPath = tempUpdatePath + strLocalPath; CreateDirtory(tempPath); FileStream fs = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write); fs.Write(bufferbyte, 0, bufferbyte.Length); srm.Close(); srmReader.Close(); fs.Close(); webRes.Close(); } InvalidateControl(); SetFormCursor(Cursors.Default); } catch(WebException ex) { SetFormCursor(Cursors.Default); System.IO.Directory.Delete(tempUpdatePath,true); MessageBox.Show("更新文件下载失败!"+ex.Message.ToString(),"错误",MessageBoxButtons.OK,MessageBoxIcon.Error); } }
/// <summary> /// 检查更新文件 /// </summary> /// <param name="serverXmlFile"></param> /// <param name="localXmlFile"></param> /// <param name="updateFileList"></param> /// <returns></returns> public int CheckForUpdate() { string localXmlFile = Application.StartupPath + "\\UpdateList.xml"; if (!File.Exists(localXmlFile)) { return(-1); } XmlFiles updaterXmlFiles = new XmlFiles(localXmlFile); string tempUpdatePath = Environment.GetEnvironmentVariable("Temp") + "\\" + "_" + updaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value + "_" + "y" + "_" + "x" + "_" + "m" + "_" + "\\"; this.UpdaterUrl = updaterXmlFiles.GetNodeValue("//Url") + "/UpdateList.xml"; this.DownAutoUpdateFile(tempUpdatePath); string serverXmlFile = tempUpdatePath + "\\UpdateList.xml"; if (!File.Exists(serverXmlFile)) { return(-1); } XmlFiles serverXmlFiles = new XmlFiles(serverXmlFile); XmlFiles localXmlFiles = new XmlFiles(localXmlFile); XmlNodeList newNodeList = serverXmlFiles.GetNodeList("AutoUpdater/Files"); XmlNodeList oldNodeList = localXmlFiles.GetNodeList("AutoUpdater/Files"); int k = 0; for (int i = 0; i < newNodeList.Count; i++) { string [] fileList = new string[3]; string newFileName = newNodeList.Item(i).Attributes["Name"].Value.Trim(); string newVer = newNodeList.Item(i).Attributes["Ver"].Value.Trim(); ArrayList oldFileAl = new ArrayList(); for (int j = 0; j < oldNodeList.Count; j++) { string oldFileName = oldNodeList.Item(j).Attributes["Name"].Value.Trim(); string oldVer = oldNodeList.Item(j).Attributes["Ver"].Value.Trim(); oldFileAl.Add(oldFileName); oldFileAl.Add(oldVer); } int pos = oldFileAl.IndexOf(newFileName); if (pos == -1) { fileList[0] = newFileName; fileList[1] = newVer; k++; } else if (pos > -1 && newVer.CompareTo(oldFileAl[pos + 1].ToString()) != 0) { fileList[0] = newFileName; fileList[1] = newVer; k++; } } return(k); }
private void FrmUpdate_Load(object sender, System.EventArgs e) { panel2.Visible = false; btnFinish.Visible = false; string localXmlFile = Application.StartupPath + "\\UpdateList.xml"; string serverXmlFile = string.Empty; try { //从本地读取更新配置文件信息 TempLog.Debug("准备加载启动路径下的UpdateList.xml更新文件!"); updaterXmlFiles = new XmlFiles(localXmlFile); mainAppExe = updaterXmlFiles.GetNodeValue("//EntryPoint"); TempLog.Debug("加载启动路径下的UpdateList.xml更新文件并读取更新完需执行的exe文件名完毕!"); } catch (Exception ex) { TempLog.Info("加载UpdateList.xml出现异常:" + ex); //MessageBox.Show("配置文件出错!","错误",MessageBoxButtons.OK,MessageBoxIcon.Error); this.StartMainApplication(); return; } //获取服务器地址 updateUrl = updaterXmlFiles.GetNodeValue("//Url"); AppUpdater appUpdater = new AppUpdater(); appUpdater.UpdaterUrl = updateUrl + "UpdateList.xml"; //与服务器连接,下载更新配置文件 try { TempLog.Debug("准备下载更新配置文件列表UpdateList.xml"); tempUpdatePath = Environment.GetEnvironmentVariable("Temp") + "\\" + "_" + updaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value + "_" + "y" + "_" + "x" + "_" + "m" + "_" + "\\"; appUpdater.DownAutoUpdateFile(tempUpdatePath); TempLog.Debug("完成下载更新配置文件列表UpdateList.xml"); } catch (Exception ex) { TempLog.Info("下载更新配置文件列表UpdateList.xml出现异常:" + ex); //MessageBox.Show("与服务器连接失败,操作超时!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information); this.StartMainApplication(); return; } //获取更新文件列表 Hashtable htUpdateFile = new Hashtable(); serverXmlFile = tempUpdatePath + "\\UpdateList.xml"; if (!File.Exists(serverXmlFile)) { return; } availableUpdate = appUpdater.CheckForUpdate(serverXmlFile, localXmlFile, out htUpdateFile); if (availableUpdate > 0) { for (int i = 0; i < htUpdateFile.Count; i++) { string [] fileArray = (string [])htUpdateFile[i]; lvUpdateList.Items.Add(new ListViewItem(fileArray)); } } this.lbFileListHint.Text = string.Format("共{0}个文件待更新,准备更新中{1}", lvUpdateList.Items.Count.ToString(), string.Empty); btnNext_Click(null, null); // else // btnNext.Enabled = false; }
/// <summary> /// �������ļ� /// </summary> /// <param name="serverXmlFile"></param> /// <param name="localXmlFile"></param> /// <param name="updateFileList"></param> /// <returns></returns> public int CheckForUpdate() { string localXmlFile = Application.StartupPath + "\\UpdateList.xml"; if(!File.Exists(localXmlFile)) { return -1; } XmlFiles updaterXmlFiles = new XmlFiles(localXmlFile ); string tempUpdatePath = Environment.GetEnvironmentVariable("Temp") + "\\"+ "_"+ updaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value+"_"+"y"+"_"+"x"+"_"+"m"+"_"+"\\"; this.UpdaterUrl = updaterXmlFiles.GetNodeValue("//Url") + "/UpdateList.xml"; this.DownAutoUpdateFile(tempUpdatePath); string serverXmlFile = tempUpdatePath +"\\UpdateList.xml"; if(!File.Exists(serverXmlFile)) { return -1; } XmlFiles serverXmlFiles = new XmlFiles(serverXmlFile); XmlFiles localXmlFiles = new XmlFiles(localXmlFile); XmlNodeList newNodeList = serverXmlFiles.GetNodeList("AutoUpdater/Files"); XmlNodeList oldNodeList = localXmlFiles.GetNodeList("AutoUpdater/Files"); int k = 0; for(int i = 0;i < newNodeList.Count;i++) { string [] fileList = new string[3]; string newFileName = newNodeList.Item(i).Attributes["Name"].Value.Trim(); string newVer = newNodeList.Item(i).Attributes["Ver"].Value.Trim(); ArrayList oldFileAl = new ArrayList(); for(int j = 0;j < oldNodeList.Count;j++) { string oldFileName = oldNodeList.Item(j).Attributes["Name"].Value.Trim(); string oldVer = oldNodeList.Item(j).Attributes["Ver"].Value.Trim(); oldFileAl.Add(oldFileName); oldFileAl.Add(oldVer); } int pos = oldFileAl.IndexOf(newFileName); if(pos == -1) { fileList[0] = newFileName; fileList[1] = newVer; k++; } else if(pos > -1 && newVer.CompareTo(oldFileAl[pos+1].ToString())>0 ) { fileList[0] = newFileName; fileList[1] = newVer; k++; } } return k; }
private void DownUpdateFile() { mainAppExe = updaterXmlFiles.GetNodeValue("//EntryPoint"); Process [] allProcess = Process.GetProcesses(); foreach (Process p in allProcess) { if (p.ProcessName.ToLower() + ".exe" == mainAppExe.ToLower()) { for (int i = 0; i < p.Threads.Count; i++) { p.Threads[i].Dispose(); } p.Kill(); isRun = true; } } bool isFinish = false; WebClient wcClient = AppUpdater.CreateClient(); WebResponse webRes = null; WebRequest webReq = null; for (int i = 0; i < this.lvUpdateList.Items.Count; i++) { string UpdateFile = lvUpdateList.Items[i].Text.Trim(); //string UpdateFile = WindowFormDelegate.GetListViewText(lvUpdateList, i); string updateFileUrl = updateUrl + UpdateFile; long fileLength = 0; WindowFormDelegate.SetMainThreadHint(lbFileListHint, string.Format("共{0}个文件待更新,准备更新第{1}个文件中", lvUpdateList.Items.Count.ToString(), (i + 1).ToString())); try { TempLog.Debug(string.Format("下载更新文件{0},创建WebRequest", updateFileUrl)); webReq = AppUpdater.Create(updateFileUrl); TempLog.Debug("完成创建WebRequest"); TempLog.Debug("下载更新文件,准备获取WebResponse"); webRes = webReq.GetResponse(); TempLog.Debug("下载更新文件,完成获取WebResponse"); fileLength = webRes.ContentLength; WindowFormDelegate.SetMainThreadHint(this.lbState, "正在下载更新文件,请稍后..."); //lbState.Text = "正在下载更新文件,请稍后..."; pbDownFile.Value = 0; pbDownFile.Maximum = (int)fileLength; TempLog.Debug("下载更新文件,获取GetResponseStream"); Stream srm = webRes.GetResponseStream(); TempLog.Debug("下载更新文件,完成获取GetResponseStream"); StreamReader srmReader = new StreamReader(srm); byte[] bufferbyte = new byte[fileLength]; int allByte = (int)bufferbyte.Length; int startByte = 0; while (fileLength > 0) { Application.DoEvents(); int downByte = srm.Read(bufferbyte, startByte, allByte); if (downByte == 0) { break; } ; startByte += downByte; allByte -= downByte; pbDownFile.Value += downByte; float part = (float)startByte / 1024; float total = (float)bufferbyte.Length / 1024; int percent = Convert.ToInt32((part / total) * 100); this.lvUpdateList.Items[i].SubItems[2].Text = percent.ToString() + "%"; } string tempPath = tempUpdatePath + UpdateFile; CreateDirtory(tempPath); FileStream fs = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write); fs.Write(bufferbyte, 0, bufferbyte.Length); srm.Close(); srmReader.Close(); fs.Close(); } catch (WebException ex) { //MessageBox.Show("更新文件下载失败!" + ex.Message.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); // isFinish = false; // continue; Console.WriteLine("下载异常:" + ex.ToString()); } finally { if (webRes != null) { webRes.Close(); webReq.Abort(); } } if (i == this.lvUpdateList.Items.Count - 1) { isFinish = true; //this.btnFinish_Click(null, null); } } InvalidateControl(); if (isFinish) { this.CopyFileThread(); } //btnFinish_Click(null, null); else { this.StartMainApplication(); } }
/// <summary> /// 检测程序版本信息 /// </summary> /// <returns></returns> public bool CheckAppVersion(ref string msg) { if (CheckFileExist(LocalUpdateFile) == false) { msg = "本地更新配置文件不存在,更新失败!"; return(false); } try {//获得本地版本信息 _localVersion = new Version(); XmlFiles xmllocalfile = new XmlFiles(LocalUpdateFile); _localVersion.EntryPoint = xmllocalfile.GetNodeValue("//Application/EntryPoint"); _localVersion.ServerUrl = xmllocalfile.GetNodeValue("//Updater/Url"); _localVersion.StrVersion = xmllocalfile.GetNodeValue("//Application/VersionName"); _localVersion.ValueVersion = int.Parse(xmllocalfile.GetNodeValue("//Application/VersionId")); } catch (Exception ex) { msg = "本地更新配置文件出错!" + Environment.NewLine + ex.Message; return(false); } try { if (Directory.Exists(LocalFileDir)) { Directory.Delete(LocalFileDir, true); } Directory.CreateDirectory(LocalFileDir); //下载服务端更新文件到本地客户端 DownloadFile(ServerUpdateFile, ServerUpdateFileClone); } catch (Exception ex) { LogHelper.WriteException(ex); msg = "当前主程序版本:" + (_localVersion != null ? _localVersion.StrVersion : "") + ",自动更新与服务器连接失败!" + Environment.NewLine + "请检查您的网络或联系维护人员。"; return(false); } if (File.Exists(ServerUpdateFileClone) == false) { msg = "更新配置文件下载失败,无法更新!"; return(false); } //获得服务端更新版本列表 msg = string.Empty; ServerVersions = GetServerVersions(ref msg); if (string.IsNullOrEmpty(msg) == false) { return(false); } // if (_localVersion.StrVersion == _newVersion.StrVersion && _localVersion.ValueVersion == _newVersion.ValueVersion || _localVersion.ValueVersion >= _newVersion.ValueVersion) { msg = string.Format("当前主程序版本:{0},已经是最新版本,无需更新。", _localVersion.StrVersion); if (Directory.Exists(LocalFileDir)) { Directory.Delete(LocalFileDir, true); } return(false); } msg = "发现最新版本"; return(true); }
//�Ա�XML�ļ�����Ƿ���������Ŀ private void XMLCheckUpdate() { label1.Text = "���ڼ����£����Ժ�..."; string localXmlFile = Application.StartupPath + "\\Update\\UpdateList.xml"; string serverXmlFile = string.Empty; try { //�ӱ��ض�ȡ���������ļ���Ϣ updaterXmlFiles = new XmlFiles(localXmlFile); } catch { MessageBox.Show("���������ļ�����!", "����", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); return; } //��ȡ��������ַ updateUrl = updaterXmlFiles.GetNodeValue("//Url"); AppUpdater appUpdater = new AppUpdater(); appUpdater.UpdaterUrl = updateUrl + "/UpdateList.xml"; appUpdater.UpdaterUrl1 = updateUrl + "/Update.xml"; //�����������,���ظ��������ļ� try { tempUpdatePath = Environment.GetEnvironmentVariable("Temp") + "\\" + "_" + updaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value + "_" + "y" + "_" + "x" + "_" + "m" + "_" + "\\";//�������ļ���ʱ�ļ�����·�� tempUpdatePath1 = Environment.GetEnvironmentVariable("Temp") + "\\" + "_" + updaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value + "_" + "y" + "_" + "x" + "_" + "m" + "_" + "\\" + "ISoft\\Update\\";//�����ļ���ʱ�ļ�·�� appUpdater.DownAutoUpdateFile(tempUpdatePath1); } catch { MessageBox.Show("�����������ʧ��,������ʱ!", "��ʾ", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); return; } //��ȡ�����ļ��б� Hashtable htUpdateFile = new Hashtable(); serverXmlFile = tempUpdatePath1 + "\\UpdateList.xml"; if (!File.Exists(serverXmlFile)) { return; } availableUpdate = appUpdater.CheckForUpdate(serverXmlFile, localXmlFile, out htUpdateFile); if (availableUpdate > 0) { for (int i = 0; i < htUpdateFile.Count; i++) { string[] fileArray = (string[])htUpdateFile[i]; lvUpdateList1.Items.Add(new ListViewItem(fileArray[0])); if (fileArray[0] == "ISoft\\ISoft.exe") { fileArray[0] = "������"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\Update\\AutoUpdate.exe") { fileArray[0] = "�Զ����³���"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\HotTools\\FileDestrory\\FileDestory.exe") { fileArray[0] = "�ļ������"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\HotTools\\Individuation\\Individuation.exe") { fileArray[0] = "���Ի�"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\HotTools\\RubbishCleaner\\RubbishCleaner.exe") { fileArray[0] = "��������"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\SysOptimizedTools\\OSSpeed\\OSSpeed.exe") { fileArray[0] = "ϵͳ����"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\SysOptimizedTools\\ScanLargeFile\\ScanLargeFile.exe") { fileArray[0] = "���ļ�ɨ��"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\SysTools\\DefaultSet\\DefaultSet.exe") { fileArray[0] = "Ĭ���������"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\SysTools\\ReadText\\ReadText.exe") { fileArray[0] = "�����ʶ���"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\SysTools\\FileMonitor\\FileMonitor.exe") { fileArray[0] = "���̼���"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\SysTools\\TimeSyn\\TimeSyn.exe") { fileArray[0] = "ʱ��ͬ������"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\OtherTools\\VideoRec\\VideoRec.exe") { fileArray[0] = "��Ƶ¼����"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\OtherTools\\FileSplitAndJion\\FileSplitAndJion.exe") { fileArray[0] = "�ļ��ָ���ϲ�"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\OtherTools\\CompTxt\\CompTxt.exe") { fileArray[0] = "�ļ����ݱȽ���"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\OtherTools\\ThunderEncodeDecode\\ThunderEncodeDecode.exe") { fileArray[0] = "Ѹ��ַ������"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } } } if (availableUpdate == 0) { InvalidateControl1(); } else { label1.Text = "����Ϊ�����ļ��б����������һ������ʼ����"; btnNext.Visible = true; } }
//对比XML文件检查是否有升级条目 private void XMLCheckUpdate() { label1.Text = "正在检查更新,请稍候..."; string localXmlFile = Application.StartupPath + "\\Update\\UpdateList.xml"; string serverXmlFile = string.Empty; try { //从本地读取更新配置文件信息 updaterXmlFiles = new XmlFiles(localXmlFile); } catch { MessageBox.Show("本地配置文件出错!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); return; } //获取服务器地址 updateUrl = updaterXmlFiles.GetNodeValue("//Url"); AppUpdater appUpdater = new AppUpdater(); appUpdater.UpdaterUrl = updateUrl + "/UpdateList.xml"; appUpdater.UpdaterUrl1 = updateUrl + "/Update.xml"; //与服务器连接,下载更新配置文件 try { tempUpdatePath = Environment.GetEnvironmentVariable("Temp") + "\\" + "_" + updaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value + "_" + "y" + "_" + "x" + "_" + "m" + "_" + "\\"; //非配置文件临时文件顶级路径 tempUpdatePath1 = Environment.GetEnvironmentVariable("Temp") + "\\" + "_" + updaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value + "_" + "y" + "_" + "x" + "_" + "m" + "_" + "\\" + "ISoft\\Update\\"; //配置文件临时文件路径 appUpdater.DownAutoUpdateFile(tempUpdatePath1); } catch { MessageBox.Show("与服务器连接失败,操作超时!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); return; } //获取更新文件列表 Hashtable htUpdateFile = new Hashtable(); serverXmlFile = tempUpdatePath1 + "\\UpdateList.xml"; if (!File.Exists(serverXmlFile)) { return; } availableUpdate = appUpdater.CheckForUpdate(serverXmlFile, localXmlFile, out htUpdateFile); if (availableUpdate > 0) { for (int i = 0; i < htUpdateFile.Count; i++) { string[] fileArray = (string[])htUpdateFile[i]; lvUpdateList1.Items.Add(new ListViewItem(fileArray[0])); if (fileArray[0] == "ISoft\\ISoft.exe") { fileArray[0] = "主程序"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\Update\\AutoUpdate.exe") { fileArray[0] = "自动更新程序"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\HotTools\\FileDestrory\\FileDestory.exe") { fileArray[0] = "文件粉碎机"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\HotTools\\Individuation\\Individuation.exe") { fileArray[0] = "个性化"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\HotTools\\RubbishCleaner\\RubbishCleaner.exe") { fileArray[0] = "垃圾清理"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\SysOptimizedTools\\OSSpeed\\OSSpeed.exe") { fileArray[0] = "系统加速"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\SysOptimizedTools\\ScanLargeFile\\ScanLargeFile.exe") { fileArray[0] = "大文件扫描"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\SysTools\\DefaultSet\\DefaultSet.exe") { fileArray[0] = "默认软件设置"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\SysTools\\ReadText\\ReadText.exe") { fileArray[0] = "语音朗读机"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\SysTools\\FileMonitor\\FileMonitor.exe") { fileArray[0] = "磁盘监视"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\SysTools\\TimeSyn\\TimeSyn.exe") { fileArray[0] = "时间同步助手"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\OtherTools\\VideoRec\\VideoRec.exe") { fileArray[0] = "视频录制器"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\OtherTools\\FileSplitAndJion\\FileSplitAndJion.exe") { fileArray[0] = "文件分割与合并"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\OtherTools\\CompTxt\\CompTxt.exe") { fileArray[0] = "文件内容比较器"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } if (fileArray[0] == "ISoft\\AdvancedFunctions\\OtherTools\\ThunderEncodeDecode\\ThunderEncodeDecode.exe") { fileArray[0] = "迅雷地址解码器"; lvUpdateList.Items.Add(new ListViewItem(fileArray)); continue; } } } if (availableUpdate == 0) { InvalidateControl1(); } else { label1.Text = "以下为更新文件列表,请点击“下一步”开始更新"; btnNext.Visible = true; } }
private void FrmUpdate_Load(object sender, System.EventArgs e) { panel2.Visible = false; btnFinish.Visible = false; string localXmlFile = Application.StartupPath + "\\UpdateList.xml"; string serverXmlFile = string.Empty; try { //从本地读取更新配置文件信息 updaterXmlFiles = new XmlFiles(localXmlFile ); } catch { MessageBox.Show("配置文件出错!","错误",MessageBoxButtons.OK,MessageBoxIcon.Error); this.Close(); return; } //获取服务器地址 updateUrl = updaterXmlFiles.GetNodeValue("//Url"); AppUpdater appUpdater = new AppUpdater(); appUpdater.UpdaterUrl = updateUrl + "/UpdateList.xml"; //与服务器连接,下载更新配置文件 try { tempUpdatePath = Environment.GetEnvironmentVariable("Temp") + "\\"+ "_"+ updaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value+"_"+"y"+"_"+"x"+"_"+"m"+"_"+"\\"; appUpdater.DownAutoUpdateFile(tempUpdatePath); } catch { MessageBox.Show("与服务器连接失败,操作超时!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information); this.Close(); return; } //获取更新文件列表 Hashtable htUpdateFile = new Hashtable(); serverXmlFile = tempUpdatePath + "\\UpdateList.xml"; if(!File.Exists(serverXmlFile)) { return; } availableUpdate = appUpdater.CheckForUpdate(serverXmlFile,localXmlFile,out htUpdateFile); if (availableUpdate > 0) { for(int i=0;i<htUpdateFile.Count;i++) { string [] fileArray =(string []) htUpdateFile[i]; lvUpdateList.Items.Add(new ListViewItem(fileArray)); } } // else // btnNext.Enabled = false; }