第一次在cnblogs發文章,沒的什麼經驗,說的不好請大家見諒.
之前開發一套應用系統,採用了C/S模式,對客戶端的應用程序自動升級提出了一些要求。
我便利用WebClient做了一下這個自動升級系統,在應用中還算不錯。今日特地貢獻出來,希望給大家一些借鑑。
系統分爲3個部分:
1.Update.dll:供主應用程序調用的檢測升級模塊。
2.Update.exe:升級的主程序.
3.升級文件的服務器端配置文件和更新文件.需要WEB服務器支持。
第一部分:服務器存放的配置文件。
假設配置文件放在一個web服務器的某個目錄下面。如:http://192.168.0.1/UpdateFiles
目錄結構如下:
update.exe
update.xml
update/目錄存放需要更新的文件列表
update.xml文件爲升級調用的配置文件,如下:
<?xml version="1.0" encoding="utf-8" ?>
<Product>
<Version>1.6.2.1</Version>
<Description>2007.4.28升級版本</Description>
<FileList>
<Item Name="mis.exe" FileURL="http://192.168.0.1/UpdateFiles/Updatetmis.exe" Folder="" />
<Item Name="config.ini" FileURL="http://192.168.0.1/UpdateFiles/Update/config.ini" Folder="" />
<Item Name="update.dll" FileURL="http://192.168.0.1/UpdateFiles/Update/update.dll" Folder="" />
</FileList>
</Product>
配置文件主要提供了當前服務器存放的系統版本號,已經相關的文件列表。相信大家都明白什麼意思,不多說了。
第二部分:檢測升級Update.dll
升級模塊爲了方便程序調用,單獨封裝在一個dll中,主程序只需要直接引用調用即可。代碼如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Xml;
/*
系統升級類
*/
namespace Update
{
public class AutoUpdate
{
private WebClient client;
private XmlDocument doc;
public string Version = "";
public void LoadUpdateXML()
{
//獲取服務器信息
client = new WebClient();
doc = new XmlDocument();
try
{
doc.Load(client.OpenRead(@"http://192.168.0.1/UpdateFiles/Update.xml"));
client = null;
//分析文件
XmlNode node;
node = doc.SelectSingleNode("Product/Version");
if (node != null)
{
Version = node.InnerText.Trim();
}
}
catch
{
MessageBox.Show("無法取得更新文件!");
}
}
/// <summary>
/// 判斷是否需要升級
/// </summary>
/// <returns></returns>
public bool NeedUpdate()
{
LoadUpdateXML();
//MessageBox.Show(Version + "||" + Application.ProductVersion);
if (Version.Trim().CompareTo(Application.ProductVersion.Trim()) > 0)
return true;
return false;
}
/// <summary>
/// 開始升級,
/// </summary>
public void Update()
{
if (NeedUpdate())
{
MessageBox.Show("已經有更新的程序,點擊確定馬上啓動升級程序。");
//下載服務器最新的升級程序,並且運行,退出本程序
client = new WebClient();
client.DownloadFile(@"http://192.168.0.1/UpdateFiles/update.exe", Application.StartupPath + "//update.exe");
System.Diagnostics.Process.Start(Application.StartupPath + "//update.exe");
Application.ExitThread();
Application.Exit();
}
}
}
}
第三部分:更新程序update.exe
程序加載的時候從服務器讀取文件列表,並且下載到本地執行目錄,完成升級後自動啓動主程序。
下載文件使用DownloadFile類,如下:
DownloadFile df = new DownloadFile();
// 文件的服務器地址
df.DownloadUrl = serverFile;
//下載本地的路徑
df.DownloadFileName = localFile;
df.Download();
具體如何設計界面,因人而異,只是給出一個提示,請讀者自己去完成。
主應用程序的調用Update.dll後如何檢測呢?
Update.AutoUpdate up=new Update.AutoUpdate();
if(up.NeedUpdate())
{
up.Update();
}
暫時就寫到這裏,有需要幫助的朋友請加我qq:38041762 或者email:gofixiao#126.com(請將#換成@)
補上demo:
/Files/gofixiao/Update_demo.rar