WinForm程序?qū)崿F(xiàn)在線更新軟件功能的具體步驟
前言
有Winform程序 LWH.exe,現(xiàn)需要實現(xiàn)遠程升級功能,參考網(wǎng)上的相關方案實現(xiàn)步驟如下:
1、在遠程服務器上建立FTP站點,將更新文件及更新信息放到相關文件夾中

其中,updates.json內(nèi)容如下:
{
"latestversion": "3.0.3",
"downloadurl": "http://***.***.***.***:****/lwh/update303.zip",
"changelog": "更改注冊機制",
"mandatory": true
}
latestversion代表提供更新的版本號,downloadurl表示更新包的下載路徑,這里將需要更新的文件壓縮成zip文件
update303.zip即為需要更新的文件
2、在工程下App.config中添加key為Version的字段來表示當前軟件版本號
<configuration>
...
<appSettings>
<add key="Version" value="3.0.2" />
</appSettings>
</configuration>
在生成的文件中該.config對應的是 應用程序名.exe.config,比如我的應用程序 是LWH.exe,則在打包更新包時應將LWH.exe.config一起打包,這樣更新完軟件后,軟件版本號則更新到新的版本號
程序中獲取當前版本號的代碼為:
version = System.Configuration.ConfigurationManager.AppSettings["Version"].ToString();

3、在解決方案中,新建一個winform應用項目update,用以從服務器上下載更新包,并解壓到指定文件夾替換相關文件實現(xiàn)更新

放置一個progressBar用來表示下載進度,放置一個label用來進行提示,代碼如下:
private string url;//下載路徑
public static FastZip fz = new FastZip();
public update(string[] args)
{
InitializeComponent();
if (args == null || args.Count() == 0)
url = "http://***.***.***.***:**/lwh/update.zip";//沒有傳入地址時使用默認地址
else
url = args[0];
}
private void update_Load(object sender, EventArgs e)
{
updateprocess();
}
private void updateprocess()
{
try
{
WebClient wc = new WebClient();
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
wc.DownloadFileAsync(new Uri(url), Application.StartupPath + "\update.zip");
}
catch(Exception er)
{
label1.Text = "下載失敗:"+er.Message;
}
}
private void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Action act = () =>
{
this.progressBar1.Value = e.ProgressPercentage;
this.label1.Text = "正在下載...";
//this.label1.Text = e.ProgressPercentage + "%";
};
this.Invoke(act);
if (e.ProgressPercentage == 100)
{
//下載完成之后開始覆蓋
this.label1.Text = "正在解壓...";
try
{
var result = Compress(Application.StartupPath, Application.StartupPath + "\update.zip",null);
//var result = unZip(Application.StartupPath + "\update.rar", @"..LWH");
if (result== "Success!")
{
progressBar1.Value = 100;
this.label1.Text = "準備安裝...";
//備份之前數(shù)據(jù)庫
var dbFile = Application.StartupPath + "/Data/TestDb.db";
if (File.Exists(dbFile))
{
var bakFile = Application.StartupPath + "/backup/" + DateTime.Now.ToString("yyyyMMddHHmmssms") + ".bak";
var bakDirectory = Path.GetDirectoryName(bakFile);
DirectoryInfo directoryInfo = new DirectoryInfo(bakDirectory);
if (!directoryInfo.Exists)
{
directoryInfo.Create();
}
else
{
//刪除7天前的備份文件
var files = directoryInfo.GetFiles();
if (files != null && files.Length > 0)
{
foreach (var file in files)
{
if (file.CreationTime.AddDays(7) < DateTime.Now)
{
file.Delete();
}
}
}
}
//備份文件
File.Move(dbFile, bakFile);
}
this.label1.Text = "更新完成";
var mainFile =Application.StartupPath+"/LWH.exe";//重新啟動軟件
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = mainFile;
p.StartInfo.CreateNoWindow = true;
p.Start();
this.Close();
}
else
{
MessageBox.Show("更新失敗:"+result);
this.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("更新失敗", ex.Message);
this.Close();
}
}
}
/// <summary>
/// 解壓Zip
/// </summary>
/// <param name="DirPath">解壓后存放路徑</param>
/// <param name="ZipPath">Zip的存放路徑</param>
/// <param name="ZipPWD">解壓密碼(null代表無密碼)</param>
/// <returns></returns>
public string Compress(string DirPath, string ZipPath, string ZipPWD)
{
string state = "Fail!";
try
{
fz.Password = ZipPWD;
fz.ExtractZip(ZipPath, DirPath, "");
state = "Success!";
}
catch (Exception ex)
{
state += "," + ex.Message;
}
return state;
}
4、將生成的update.exe拷貝到主應用程序(LWH.exe)軟件目錄下以供調(diào)用,在LWH的檢測更新按鍵下加入以下代碼:
private void buttonXUpdate_Click(object sender, EventArgs e)
{
try
{
string rXml = string.Empty;
HttpWebRequest myHttpWebRequest = System.Net.WebRequest.Create(backdata.updateUrl) as HttpWebRequest;
myHttpWebRequest.KeepAlive = false;
myHttpWebRequest.AllowAutoRedirect = false;
myHttpWebRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)";
myHttpWebRequest.Timeout = 5000;
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
using (HttpWebResponse res = (HttpWebResponse)myHttpWebRequest.GetResponse())
{
if (res.StatusCode == HttpStatusCode.OK || res.StatusCode == HttpStatusCode.PartialContent)//返回為200或206
{
string dd = res.ContentEncoding;
System.IO.Stream strem = res.GetResponseStream();
System.IO.StreamReader r = new System.IO.StreamReader(strem);
rXml = r.ReadToEnd();
}
else
{
MessageBox.Show("無法連接到遠程服務器");
return;
}
}
updateInf updateinf = JsonConvert.DeserializeObject<updateInf>(rXml);
if (string.Compare(updateinf.latestversion, version) > 0)
{
if (MessageBox.Show("有新版本:" + updateinf.latestversion + "rn" + "更新內(nèi)容:" + updateinf.changelog + "rn是否進行更新?", "提示", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
{
return;
}
var mainFile = Application.StartupPath + @"update.exe";
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = mainFile;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.Arguments = updateinf.downloadurl;
p.Start();
this.Close();
}
else
{
MessageBox.Show("沒有更新版本了!");
}
}
catch(Exception er)
{
MessageBox.Show("檢查更新出現(xiàn)錯誤:" + er.Message);
}
}
updateInf為定義的更新文件信息類:
public class updateInf
{
public string latestversion;
public string downloadurl;
public string changelog;
public string mandatory;
}
點擊"檢查更新"按鍵后,首先從服務器讀取updates.json,解析出服務器上的版本號和當前軟件的版本進行比對,如果比當前版本新,則提示進行更新,如果選擇進行更新則啟動update.exe并傳入updates.json中提供的更新包下載地址,啟動后立即關閉主程序。




最后,可以對update稍作修改,在啟動的時候傳入?yún)?shù)中再增加exe名稱,如
public update(string[] args)
{
InitializeComponent();
if (args == null || args.Count() < 2)
{
//url = "http://116.63.143.64:9010/lwh/update.zip";
}
else
{
url = args[0];
exename = args[1];
}
}
升級完畢時,重啟程序 改成:
if (exename != "")
{
var mainFile = Application.StartupPath +"/"+ exename;
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = mainFile;
p.StartInfo.CreateNoWindow = true;
p.Start();
this.Close();
}
這就可以將update很便捷地添加到其他工程里面實現(xiàn)遠程升級功能
最后
以上就是WinForm程序?qū)崿F(xiàn)在線更新軟件功能的具體步驟的詳細內(nèi)容,更多關于WinForm在線更新軟件的資料請關注腳本之家其它相關文章!
相關文章
C#將數(shù)字轉(zhuǎn)換成字節(jié)數(shù)組的方法
這篇文章主要介紹了C#將數(shù)字轉(zhuǎn)換成字節(jié)數(shù)組的方法,涉及C#字符串操作的技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04
C#使用Spire.XLS讀取Excel數(shù)據(jù)的代碼示例
在現(xiàn)代企業(yè)應用中,Excel文件扮演著至關重要的角色,無論是數(shù)據(jù)導入、報表生成、還是數(shù)據(jù)分析,都離不開對Excel數(shù)據(jù)的處理,對于C#開發(fā)者而言,如何高效、穩(wěn)定地在應用程序中C#讀取Excel內(nèi)容,常常是一個需要面對的挑戰(zhàn),本文介紹了C#如何使用Spire.XLS讀取Excel數(shù)據(jù)2025-09-09
C# 中 System.Index 結構體和 Hat 運算符(^)的使用示例
這篇文章主要介紹了C# 中 System.Index 結構體和 Hat 運算符(^)的使用示例,幫助大家更好的理解和使用C#,感興趣的朋友可以了解下2020-09-09

