首頁/ 汽車/ 正文

Winform 自動升級,強制升級

抽出時間整理下升級這塊的功能,並封裝一個升級工具包。

Winform 自動升級,強制升級

作為winform 程式設計師都有一個C/S端程式繞不過的問題。那就是如何升級程式?

程序升級兩種1。啟動時強制更新 2。自動、手動獲取更新,並確認是否升級。

今天咱們介紹,自動或者手動更新功能。

首先思考如何升級? 升級肯定要有一個新的升級檔案包,還有一個本地版本和伺服器版本號,因為這樣才能對比是否升級。

看下下面的升級提示:

Winform 自動升級,強制升級

等待上面的升級下載程式完畢即可。會自動替換主程式,並啟動主程式。

設計思路:我繪製了一張圖可以從圖中看。

Winform 自動升級,強制升級

1。 主程式開始升級,會檢查是否有升級器有就啟動下載,沒有就去先下載升級器

2。 啟動升級器,下載檔案,下載後解壓替換主程式。 並啟動主程式。

下載器的一些程式碼:

using System;using System。Collections。Generic;using System。ComponentModel;using System。Configuration;using System。Data;using System。Diagnostics;using System。Drawing;using System。IO;using System。Linq;using System。Text;using System。Threading;using System。Windows。Forms; namespace AutoUpdate{ public partial class FrmMain : Form { public FrmMain() { InitializeComponent(); } string Rootpath = Environment。CurrentDirectory; ///

/// 本地儲存目錄 /// string ZipFilePath = Common。FilePathConfig。DownZIPPath; /// /// 本地解壓目錄 /// string UnFilePath = Common。FilePathConfig。UnDownZIPPath; /// /// 開始升級程式客戶端 author:huochengyan /// /// /// private void button1_Start_Click(object sender, EventArgs e) { timer1。Enabled = true; Thread th = new Thread(StartUpdate); th。IsBackground = true; th。Start(); } /// /// 開始下載檔案 升級 /// private void StartUpdate() { bool result = Common。HttpHelper。HttpDownload(Common。FilePathConfig。DownZIPUrl, ZipFilePath, this。progressBar1, this。label2_tishi); timer1。Enabled = false; if (result) { RefThisForm(“下載成功!”); Thread。Sleep(100); RefThisForm(“正在解壓,請稍後”); if (!Directory。Exists(UnFilePath)) Directory。CreateDirectory(UnFilePath); //UnFilePath = new FileInfo(ZipFilePath)。DirectoryName; string reusult = Common。ZIPHelper。UnZipFile(ZipFilePath,UnFilePath); if (reusult != “”) { RefThisForm(“解壓成功!”); CheckUnZIPFile(reusult); } else { RefThisForm(“解壓失敗!壓縮包路徑:” + ZipFilePath); } } else { MsgShow(“下載失敗!”); } } private void FrmMain_Load(object sender, EventArgs e) { InitConfig(); FrmMain。CheckForIllegalCrossThreadCalls = false; //刪除陳舊的歷史下載記錄ZIP資訊 try { File。Delete(ZipFilePath); } catch (Exception ex) { } //檢查下載器檔案的dll button1_Start_Click(null, null); } private void CheckFile() { string UnZipdllPath = Rootpath + “/ICSharpCode。SharpZipLib。dll”; if (!File。Exists(UnZipdllPath)) { MessageBox。Show(“下載器檔案丟失:ICSharpCode。SharpZipLib。dll”); } } private void InitConfig() { try { Configuration config = ConfigurationManager。OpenExeConfiguration(ConfigurationUserLevel。None); Common。FilePathConfig。DownZIPUrl = config。AppSettings。Settings[“softURL”]。Value; } catch (Exception ex) { MessageBox。Show(“讀取配置失敗!” + ex。ToString()); } } /// /// 檢查檔案 解壓 /// /// private void CheckUnZIPFile(string UnZipFileDirPath) { string mainexe = UnZipFileDirPath + “/LongDeTools。exe”; Directory。SetCurrentDirectory(Directory。GetParent(UnZipFileDirPath)。FullName); string OldFolder = Directory。GetCurrentDirectory(); if (!File。Exists(mainexe)) { MessageBox。Show(“未能找到主程式:” + mainexe); return; } else { //覆蓋源目錄檔案 // string result=Common。FileHelper。CopyFolder(OldFolder,UnZipFileDirPath); //MessageBox。Show(“請確認開始替換原始檔案!”); RefThisForm(“安裝中。。。”); //RefThisForm(“替換原始主程式中。。。。”); bool result1=Common。FileHelper。CopyOldLabFilesToNewLab(UnZipFileDirPath,OldFolder,0); if (result1) { RefThisForm(“安裝中。。。”); //RefThisForm(“替換原始程式完畢。。。。”); //清空解壓的檔案 FileInfo fileinfo = new FileInfo(UnZipFileDirPath); try { if (Directory。Exists(fileinfo。FullName)) { // MessageBox。Show(“要刪除的檔案目錄:” + fileinfo。FullName); Common。FileHelper。DelectDir(fileinfo。FullName); Common。FileHelper。DelectDir(Common。FilePathConfig。UnDownZIPPath); GC。Collect(); } } catch (Exception ex) { MsgShow(“清理下載檔案垃圾失敗!”+ex。ToString()); } } else { MsgShow(“升級失敗!”); } } //2。 啟動新下載的程式 StartNewSystem(); GC。Collect(); } /// /// 啟動最新下載的程式 /// private void StartNewSystem() { //string path = Environment。CurrentDirectory; //Directory。SetCurrentDirectory(Directory。GetParent(path)。FullName); //path = Directory。GetCurrentDirectory(); //string mainexe = path + “/LongDeTools。exe”; string path=System。Windows。Forms。Application。StartupPath; string mainexe = “”; if (Directory。Exists(path)) { mainexe = Directory。GetParent(path)+“/” + “LongDeTools。exe”; } if (File。Exists(mainexe)) { Process。Start(mainexe); RefThisForm(“升級完成”); MessageBox。Show(“升級到最新版本!!!”); this。Close(); } else { MsgShow(“要啟動的檔案不存在!!!”+mainexe); } ///清理下載的檔案的快取垃圾 GC。Collect(); } private void RefThisForm(string text) { this。Text = text; } /// /// 時間 戳 事件 /// /// /// private void timer1_Tick(object sender, EventArgs e) { //Console。WriteLine(“時間timer\r\n”+DateTime。Now。ToString()+“\r\n”); label2_tishi。Text = progressBar1。Value/1048576+“M/”+ progressBar1。Maximum/ 1048576 + “M”; if(progressBar1。Value== progressBar1。Maximum) label2_tishi。Text= progressBar1。Maximum / 1048576 + “M/” + progressBar1。Maximum / 1048576 + “M”; } private void MsgShow(string msg) { MessageBox。Show(msg); } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { FrmSetServer frm = new FrmSetServer(); frm。ShowDialog(); } }}

using ICSharpCode。SharpZipLib。Checksums;using ICSharpCode。SharpZipLib。Zip;using System;using System。Collections。Generic;using System。IO;using System。Linq;using System。Text;using System。Windows。Forms; namespace AutoUpdate。Common{ ///

/// 適用與ZIP壓縮 /// public class ZIPHelper { #region 壓縮 /// /// 遞迴壓縮資料夾的內部方法 /// /// 要壓縮的資料夾路徑 /// 壓縮輸出流 /// 此資料夾的上級資料夾 /// private static bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName) { bool result = true; string[] folders, files; ZipEntry ent = null; FileStream fs = null; Crc32 crc = new Crc32(); try { ent = new ZipEntry(Path。Combine(parentFolderName, Path。GetFileName(folderToZip) + “/”)); zipStream。PutNextEntry(ent); zipStream。Flush(); files = Directory。GetFiles(folderToZip); foreach (string file in files) { fs = File。OpenRead(file); byte[] buffer = new byte[fs。Length]; fs。Read(buffer, 0, buffer。Length); ent = new ZipEntry(Path。Combine(parentFolderName, Path。GetFileName(folderToZip) + “/” + Path。GetFileName(file))); ent。DateTime = DateTime。Now; ent。Size = fs。Length; fs。Close(); crc。Reset(); crc。Update(buffer); ent。Crc = crc。Value; zipStream。PutNextEntry(ent); zipStream。Write(buffer, 0, buffer。Length); } } catch { result = false; } finally { if (fs != null) { fs。Close(); fs。Dispose(); } if (ent != null) { ent = null; } GC。Collect(); GC。Collect(1); } folders = Directory。GetDirectories(folderToZip); foreach (string folder in folders) if (!ZipDirectory(folder, zipStream, folderToZip)) return false; return result; } /// /// 壓縮資料夾 /// /// 要壓縮的資料夾路徑 /// 壓縮檔案完整路徑 /// 密碼 /// 是否壓縮成功 public static bool ZipDirectory(string folderToZip, string zipedFile, string password) { bool result = false; if (!Directory。Exists(folderToZip)) return result; ZipOutputStream zipStream = new ZipOutputStream(File。Create(zipedFile)); zipStream。SetLevel(6); if (!string。IsNullOrEmpty(password)) zipStream。Password = password; result = ZipDirectory(folderToZip, zipStream, “”); zipStream。Finish(); zipStream。Close(); return result; } /// /// 壓縮資料夾 /// /// 要壓縮的資料夾路徑 /// 壓縮檔案完整路徑 /// 是否壓縮成功 public static bool ZipDirectory(string folderToZip, string zipedFile) { bool result = ZipDirectory(folderToZip, zipedFile, null); return result; } /// /// 壓縮檔案 /// /// 要壓縮的檔案全名 /// 壓縮後的檔名 /// 密碼 /// 壓縮結果 public static bool ZipFile(string fileToZip, string zipedFile, string password) { bool result = true; ZipOutputStream zipStream = null; FileStream fs = null; ZipEntry ent = null; if (!File。Exists(fileToZip)) return false; try { fs = File。OpenRead(fileToZip); byte[] buffer = new byte[fs。Length]; fs。Read(buffer, 0, buffer。Length); fs。Close(); fs = File。Create(zipedFile); zipStream = new ZipOutputStream(fs); if (!string。IsNullOrEmpty(password)) zipStream。Password = password; ent = new ZipEntry(Path。GetFileName(fileToZip)); zipStream。PutNextEntry(ent); zipStream。SetLevel(6); zipStream。Write(buffer, 0, buffer。Length); } catch { result = false; } finally { if (zipStream != null) { zipStream。Finish(); zipStream。Close(); } if (ent != null) { ent = null; } if (fs != null) { fs。Close(); fs。Dispose(); } } GC。Collect(); GC。Collect(1); return result; } /// /// 壓縮檔案 /// /// 要壓縮的檔案全名 /// 壓縮後的檔名 /// 壓縮結果 public static bool ZipFile(string fileToZip, string zipedFile) { bool result = ZipFile(fileToZip, zipedFile, null); return result; } /// /// 壓縮檔案或資料夾 /// /// 要壓縮的路徑 /// 壓縮後的檔名 /// 密碼 /// 壓縮結果 public static bool Zip(string fileToZip, string zipedFile, string password) { bool result = false; if (Directory。Exists(fileToZip)) result = ZipDirectory(fileToZip, zipedFile, password); else if (File。Exists(fileToZip)) result = ZipFile(fileToZip, zipedFile, password); return result; } /// /// 壓縮檔案或資料夾 /// /// 要壓縮的路徑 /// 壓縮後的檔名 /// 壓縮結果 public static bool Zip(string fileToZip, string zipedFile) { bool result = Zip(fileToZip, zipedFile, null); return result; } #endregion #region 解壓 /// /// 解壓功能(解壓壓縮檔案到指定目錄) /// /// 待解壓的檔案 /// 指定解壓目標目錄 /// 密碼 /// 解壓結果 public static bool UnZip(string fileToUnZip, string zipedFolder, string password) { bool result = true; FileStream fs = null; ZipInputStream zipStream = null; ZipEntry ent = null; string fileName; if (!File。Exists(fileToUnZip)) return false; if (!Directory。Exists(zipedFolder)) Directory。CreateDirectory(zipedFolder); try { zipStream = new ZipInputStream(File。OpenRead(fileToUnZip)); if (!string。IsNullOrEmpty(password)) zipStream。Password = password; while ((ent = zipStream。GetNextEntry()) != null) { if (!string。IsNullOrEmpty(ent。Name)) { fileName = Path。Combine(zipedFolder, ent。Name); fileName = fileName。Replace(‘/’, ‘\\’);//change by Mr。HopeGi if (fileName。EndsWith(“\\”)) { Directory。CreateDirectory(fileName); continue; } fs = File。Create(fileName); int size = 2048; byte[] data = new byte[size]; while (true) { size = zipStream。Read(data, 0, data。Length); if (size > 0) fs。Write(data, 0, data。Length); else break; } } } } catch { result = false; } finally { if (fs != null) { fs。Close(); fs。Dispose(); } if (zipStream != null) { zipStream。Close(); zipStream。Dispose(); } if (ent != null) { ent = null; } GC。Collect(); GC。Collect(1); } return result; } /// /// 解壓功能(解壓壓縮檔案到指定目錄) /// /// 待解壓的檔案 /// 指定解壓目標目錄 /// 解壓結果 public static bool UnZip(string fileToUnZip, string zipedFolder) { bool result = UnZip(fileToUnZip, zipedFolder, null); return result; } #endregion #region 使用GZIP解壓 public static bool UnZipFile(string zipFilePath) { if (!File。Exists(zipFilePath)) { //Console。WriteLine(“Cannot find file ‘{0}’”, zipFilePath); return false; } try { using (ZipInputStream s = new ZipInputStream(File。OpenRead(zipFilePath))) { ZipEntry theEntry; while ((theEntry = s。GetNextEntry()) != null) { //Console。WriteLine(theEntry。Name); string directoryName =Path。GetDirectoryName(theEntry。Name); string fileName = Path。GetFileName(theEntry。Name); // create directory if (directoryName。Length > 0) { Directory。CreateDirectory(directoryName); } if (fileName != String。Empty) { using (FileStream streamWriter = File。Create(theEntry。Name)) { int size = 2048; byte[] data = new byte[2048]; while (true) { size = s。Read(data, 0, data。Length); if (size > 0) { streamWriter。Write(data, 0, size); } else { break; } } } } } } return true; } catch (Exception ex) { MessageBox。Show(ex。ToString()); return false; } } /// /// 解壓檔案 /// /// ZIP路徑 /// 解壓到的路徑 /// public static string UnZipFile(string TargetFile, string fileDir) { string rootFile = “ ”; try { //讀取壓縮檔案(zip檔案),準備解壓縮 ZipInputStream s = new ZipInputStream(File。OpenRead(TargetFile。Trim())); ZipEntry theEntry; string path = fileDir; //解壓出來的檔案儲存的路徑 string rootDir = “ ”; //根目錄下的第一個子資料夾的名稱 while ((theEntry = s。GetNextEntry()) != null) { rootDir = Path。GetDirectoryName(theEntry。Name); //得到根目錄下的第一級子資料夾的名稱 if (rootDir。IndexOf(“\\”) >= 0) { rootDir = rootDir。Substring(0, rootDir。IndexOf(“\\”) + 1); } string dir = Path。GetDirectoryName(theEntry。Name); //根目錄下的第一級子資料夾的下的資料夾的名稱 string fileName = Path。GetFileName(theEntry。Name); //根目錄下的檔名稱 if (dir != “ ”) //建立根目錄下的子資料夾,不限制級別 { if (!Directory。Exists(fileDir + “\\” + dir)) { path = fileDir + “\\” + dir; //在指定的路徑建立資料夾 Directory。CreateDirectory(path); //MessageBox。Show(path); } } else if (dir == “ ” && fileName != “”) //根目錄下的檔案 { path = fileDir; rootFile = fileName; } else if (dir != “ ” && fileName != “”) //根目錄下的第一級子資料夾下的檔案 { if (dir。IndexOf(“\\”) > 0) //指定檔案儲存的路徑 { path = fileDir + “\\” + dir; } } if (dir == rootDir) //判斷是不是需要儲存在根目錄下的檔案 { path = fileDir + “\\” + rootDir; } //以下為解壓縮zip檔案的基本步驟 //基本思路就是遍歷壓縮檔案裡的所有檔案,建立一個相同的檔案。 if (fileName != String。Empty) { FileStream streamWriter = File。Create(path + “\\” + fileName); int size = 2048; byte[] data = new byte[2048]; while (true) { size = s。Read(data, 0, data。Length); if (size > 0) { streamWriter。Write(data, 0, size); } else { break; } } streamWriter。Close(); } } s。Close(); return fileDir; } catch (Exception ex) { MessageBox。Show(“解壓失敗,升級包路徑為:”+ fileDir+“\r\n”+“異常為:”+ex。ToString()); return “”; } } #endregion } }

啟動兩個下載引數:1。 下載檔案位置 2。 下載檔案版本號位置

Winform 自動升級,強制升級

做了一個配置介面:

主程式呼叫下載器:

#region 檢查更新 private void 檢查更新ToolStripMenuItem_Click(object sender, EventArgs e) { string checkVersion = “http://xxxx。com/NewVersion。txt”; string newVersion = HttpHelper。GetHttpResponse(checkVersion, 5000,null); Console。WriteLine(newVersion); Version yun = new Version(newVersion); Version ben = new Version(this。ProductVersion); if (yun > ben) { String msg = string。Format(“您當前版本:{0},最新版本為:{1},確定要升級到最新版本嗎?”, this。ProductVersion,newVersion); if (DialogResult。OK == MessageBox。Show(msg, “升級提示:升級過程中,將暫停服務!”, MessageBoxButtons。OKCancel)) { ExistDownUpdateSoft(); Process。Start(this。applicationPath + “/AutoUpdate/AutoUpdate。exe”); CloseAll(); } } else { MessageBox。Show(“已經是最新版!”); } } ///

/// 沒有升級元件就下載,有就更新。直接返回 /// /// private bool ExistDownUpdateSoft() { if (!File。Exists(this。applicationPath + “/AutoUpdate/AutoUpdate。exe”)) { FrmForm。FrmUpdate frmUpdate = new FrmForm。FrmUpdate(); DialogResult result = frmUpdate。ShowDialog(); if (result == DialogResult。OK) { return true; } } return true; } private void CloseAll() { System。Environment。Exit(0); if (myThread != null) { myThread。Abort(); } // 關閉所有的執行緒 this。Dispose(); this。Close(); } #endregion

如果將下載更新事件放到啟動初始化中,就是強制更新咯。

至此winform自動升級程式完成!!!

原始碼會開源。需要的可以私信小編……

Winform 自動升級,強制升級

相關文章

頂部