記錄一下自動更新,自己寫的,流程非常之神奇和偷懶,有興趣的自己改寫成比較不偷懶的版本吧!!!
先介紹流程:
主Form在開啟時,呼叫WebApi確認是否有更新,有則啟動更新程式進行更新作業。
Main Form:
1: public Form1()
2: {
3: InitializeComponent();
4: //呼叫WebApi
5: CheckVersion();
6: //取得檔案本版編號
7: var version = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion;
8: this.Text += " v" + version;
9: }
10:
11: private async void CheckVersion()
12: {
13: #region WebApi Get
14: //此處利用.NetFramework 4.5 之非同步方法使用,系統最低OS規格為Vista以上(XP不能安裝4.5),如要在XP使用請用傳統大腸包小腸寫法
15: var httpClient = new HttpClient();
16: var version = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion;
17: var address = new Uri("http://localhost:52666/api/OutlookApi/" + version);
18: HttpResponseMessage response = await httpClient.GetAsync(address);
19: response.EnsureSuccessStatusCode();
20: var _path = await response.Content.ReadAsStringAsync();
21: #endregion
22: string exeFile = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
23: string exeDir = Path.GetDirectoryName(exeFile);
24: string fullPath = exeDir + "\\Update.zip";
25: if (!string.IsNullOrEmpty(_path))
26: {
27: using (WebClient webClient = new WebClient())
28: {
29: try
30: {
31: webClient.DownloadFile(_path.Replace("\"", ""), fullPath);
32: MessageBox.Show("有新版本,請點選確定開始更新!!");
33: Process p = Process.Start("OutlookUpdate.exe");
34: this.Close();
35: }
36: catch
37: {
38: File.Delete(fullPath);
39: }
40: }
41: }
42: }
Web Api:
1: public class OutlookApiController : ApiController
2: {
3: // GET api/OutlookApi/5
4: public string Get(string id)
5: {
6: if (id == FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion)
7: return "";
8: else
9: {
10: //回傳更新檔所在位置
11: return "http://localhost:52666/updatedata/Export_test.zip";
12: }
13: }
14: }
Update Form:
1: using MySharpZip;
2:
3: public UpdateForm()
4: {
5: InitializeComponent();
6: update();
7: }
8:
9: private void update()
10: {
11: string exeFile = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
12: string exeDir = Path.GetDirectoryName(exeFile);
13: string fullPath = exeDir + "\\Update.zip";
14:
15: if (File.Exists(fullPath))
16: {
17: //用第三方套件提供解壓縮功能
18: CZip oZip = new CZip();
19: oZip.UnZipFile(fullPath, exeDir);
20: MessageBox.Show("更新成功!!");
21: }
22: else
23: {
24: MessageBox.Show("不需更新!!");
25: }
26:
27: Process p = Process.Start("OutlookImport.exe");
28: this.Close();
29: }
可以看到我因為偷懶,所以使用API端的檔案版本跟WinForm端的檔案版本直接做比對,此方法有缺點,所以建議把WinForm端的版本編號存至資料庫或是設定檔裡面會比較好一些。
--------------------2012-11-09 更新--------------
如遇到無法更新的,請參考PartII
