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

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

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

放置一個(gè)progressBar用來(lái)表示下載進(jìn)度,放置一個(gè)label用來(lái)進(jìn)行提示,代碼如下:
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";//沒(méi)有傳入地址時(shí)使用默認(rèn)地址
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 = "準(zhǔn)備安裝...";
//備份之前數(shù)據(jù)庫(kù)
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";//重新啟動(dòng)軟件
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代表無(wú)密碼)</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拷貝到主應(yīng)用程序(LWH.exe)軟件目錄下以供調(diào)用,在LWH的檢測(cè)更新按鍵下加入以下代碼:
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("無(wú)法連接到遠(yuǎn)程服務(wù)器");
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是否進(jìn)行更新?", "提示", 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("沒(méi)有更新版本了!");
}
}
catch(Exception er)
{
MessageBox.Show("檢查更新出現(xiàn)錯(cuò)誤:" + er.Message);
}
}
updateInf為定義的更新文件信息類:
public class updateInf
{
public string latestversion;
public string downloadurl;
public string changelog;
public string mandatory;
}
點(diǎn)擊"檢查更新"按鍵后,首先從服務(wù)器讀取updates.json,解析出服務(wù)器上的版本號(hào)和當(dāng)前軟件的版本進(jìn)行比對(duì),如果比當(dāng)前版本新,則提示進(jìn)行更新,如果選擇進(jìn)行更新則啟動(dòng)update.exe并傳入updates.json中提供的更新包下載地址,啟動(dòng)后立即關(guān)閉主程序。




最后,可以對(duì)update稍作修改,在啟動(dòng)的時(shí)候傳入?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];
}
}
升級(jí)完畢時(shí),重啟程序 改成:
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很便捷地添加到其他工程里面實(shí)現(xiàn)遠(yuǎn)程升級(jí)功能
最后
以上就是WinForm程序?qū)崿F(xiàn)在線更新軟件功能的具體步驟的詳細(xì)內(nèi)容,更多關(guān)于WinForm在線更新軟件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#將數(shù)字轉(zhuǎn)換成字節(jié)數(shù)組的方法
這篇文章主要介紹了C#將數(shù)字轉(zhuǎn)換成字節(jié)數(shù)組的方法,涉及C#字符串操作的技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04
C#使用Spire.XLS讀取Excel數(shù)據(jù)的代碼示例
在現(xiàn)代企業(yè)應(yīng)用中,Excel文件扮演著至關(guān)重要的角色,無(wú)論是數(shù)據(jù)導(dǎo)入、報(bào)表生成、還是數(shù)據(jù)分析,都離不開對(duì)Excel數(shù)據(jù)的處理,對(duì)于C#開發(fā)者而言,如何高效、穩(wěn)定地在應(yīng)用程序中C#讀取Excel內(nèi)容,常常是一個(gè)需要面對(duì)的挑戰(zhàn),本文介紹了C#如何使用Spire.XLS讀取Excel數(shù)據(jù)2025-09-09
C# 中 System.Index 結(jié)構(gòu)體和 Hat 運(yùn)算符(^)的使用示例
這篇文章主要介紹了C# 中 System.Index 結(jié)構(gòu)體和 Hat 運(yùn)算符(^)的使用示例,幫助大家更好的理解和使用C#,感興趣的朋友可以了解下2020-09-09
Unity UGUI實(shí)現(xiàn)滑動(dòng)翻頁(yè)效果
這篇文章主要為大家詳細(xì)介紹了Unity UGUI實(shí)現(xiàn)滑動(dòng)翻頁(yè)效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04

