C # method to achieve automatic software updates

This paper analyzes the examples using C # method to achieve automatic software updates, is a very useful feature, it is worth learning and reference. details as follows:

1. Overview of issues:

For a long time, the majority of programmers in the end is to use the Client / Server, or use the Browser / Server architecture debate, in which these arguments, the program maintainability of C / S structure difference, layout difficulties, upgrade convenient, high maintenance costs is a very important factor. There are many corporate users it is for this reason renounce the use of C / S. However, when an application must use the C / S structure to achieve its function well, how do we solve client deployment and automatic escalation? Deployment is very simple, just click on the installer to, the difficulty is that whenever a new version is released, the automatic upgrade. Well now, our goal is simple, we want nothing to do with the development of a specific application automatically updates your system can reuse. Now I provides an automatic upgrade system written in C # is a set of reusable for everyone.

2. The difficulty automatically upgrade existing software implementation

 First, in order to find updates on a remote server, the application must have a way to query the network, which requires network programming, simple application and communication server protocol.
 The second is to download. Download the looks do not need to consider the issue of networking, but should consider downloading the file requested by the user, and download large files without the user consent. Friendly automatically update the application will use the remaining bandwidth to download the update. It sounds simple, but it is a technical problem, fortunately, we have a solution.
 A third consideration is to use the new application to replace the original application process. The more interesting question, because it requires the code to run remove themselves from the system, there are several ways to achieve this function [5], this program is implemented to replace the function of major new version of the application by comparing the old and new versions of the date number.

3. The principle of automatic software upgrades online

 Write two programs, one is the main program; a program upgrade; all upgrade tasks are handled by the upgrade process is complete.
 . ① start the upgrade program, the upgrade program connects to the Web site, download the new main program (of course also includes support library files, XML configuration files, etc.) into a temporary folder;
 . ② upgrade to obtain your server-side XML configuration file in the new version of the program the updated version number or date or file size;
 ③ upgrade existing client applications to obtain the most recent update date or version number or file size, compare the two; If you find that the upgrade process is greater than the original date of the latest program date, whether the user is prompted to upgrade; or is using the compare existing versions with the latest version, the latest discovery of whether the user is prompted to upgrade; it was also compare with other attributes such as file size, file size upgrade program found larger than the old version the size of the program the user is prompted to upgrade. This paper compares the use of old and new versions updated number to prompt the user to upgrade.
 . ④ If you choose to upgrade, you get to download the file list to start the batch download documentation;
 . ⑤ upgrade program detects whether the old main activity, if the old main activity is closed;
 . ⑥ Remove the old main program, the temporary copy file in the folder to the appropriate location;
 . ⑦ check the status of the main program, when the state is active, a new main program is started;
 ⑧ closed upgrade, the upgrade is complete.

4. implement online upgrades of the key steps with C #

Here I primarily use date information to detect the need to download the upgrade version.

①. Prepare an XML configuration file

Name AutoUpdater.xml, functions as a template with the upgrade, display information need to be upgraded.
Name AutoUpdater.xml, functions as a template with the upgrade, display information need to be upgraded.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<?xml version="1.0"?> //xml版本号

<AutoUpdater>

<URLAddres URL="http://192.168.198.113/vbroker/log/"/>//升级文件所在服务器端的网址

<UpdateInfo>

<UpdateTime Date = "2005-02-02"/> //升级文件的更新日期

<Version Num = "1.0.0.1"/> //升级文件的版本号

</UpdateInfo>

<UpdateFileList> //升级文件列表

<UpdateFile FileName = "aa.txt"/> //共有三个文件需升级

<UpdateFile FileName = "VB40.rar"/>

<UpdateFile FileName = "VB4-1.CAB"/>

</UpdateFileList>

<RestartApp>

<ReStart Allow = "Yes"/> //允许重新启动应用程序

<AppName Name = "TIMS.exe"/> //启动的应用程序名

</RestartApp>

</AutoUpdater>

// xml version
// upgrade file server URL
// Update Date upgrade file
// version number of the upgrade file
// update the list of files
// There are three documents need to upgrade
// allowed to restart the application
// starts the application name

 From the above XML document that can be upgraded Updated document where the address of the server, upgrade the document, a list of files need to be upgraded, in which a total of three documents to be upgraded: aa.txt, VB40.rar, VB4-1.CAB. And whether to allow restart the application and restart the application name.

②. Gets the client application and the server-side upgrade program last updated date

Available () function is implemented by GetTheLastUpdateTime.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

private string GetTheLastUpdateTime(string Dir)

{

string LastUpdateTime = "";

string AutoUpdaterFileName = Dir + @"\AutoUpdater.xml";

if(!File.Exists(AutoUpdaterFileName))

return LastUpdateTime;

//打开xml文件

FileStream myFile = new FileStream(AutoUpdaterFileName,FileMode.Open);

//xml文件阅读器

XmlTextReader xml = new XmlTextReader(myFile);

while(xml.Read())

{

if(xml.Name == "UpdateTime")

{

//获取升级文档的最后一次更新日期

LastUpdateTime = xml.GetAttribute("Date");

break;

}

}

xml.Close();

myFile.Close();

return LastUpdateTime;

}

Open through XmlTextReader XML document, read the update time so as to obtain Date corresponding value, that is the last server update file update time.

Function calls to achieve:

?

1

2

3

4

5

6

//获取客户端指定路径下的应用程序最近一次更新时间

string thePreUpdateDate = GetTheLastUpdateTime(Application.StartupPath);

Application.StartupPath指客户端应用程序所在的路径。

//获得从服务器端已下载文档的最近一次更新日期

string theLastsUpdateDate = GetTheLastUpdateTime(theFolder.FullName);

theFolder.FullName指在升级文档下载到客户机上的临时文件夹所在的路径。

③. Compare Date

The client application and the date of last update server-side upgrade program last updated date comparisons.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

//获得已下载文档的最近一次更新日期

string theLastsUpdateDate = GetTheLastUpdateTime(theFolder.FullName);

if(thePreUpdateDate != "")

{

//如果客户端将升级的应用程序的更新日期大于服务器端升级的应用程序的更新日期

if(Convert.ToDateTime(thePreUpdateDate)>=Convert.ToDateTime(theLastsUpdateDate))

{

MessageBox.Show("当前软件已经是最新的,无需更新!","系统提示",MessageBoxButtons.OK,MessageBoxIcon.Information);

this.Close();

}

}

this.labDownFile.Text = "下载更新文件";

this.labFileName.Refresh();

this.btnCancel.Enabled = true;

this.progressBar.Position = 0;

this.progressBarTotal.Position = 0;

this.progressBarTotal.Refresh();

this.progressBar.Refresh();

//通过动态数组获取下载文件的列表

ArrayList List = GetDownFileList(GetTheUpdateURL(),theFolder.FullName);

string[] urls = new string[List.Count];

List.CopyTo(urls, 0);

The date and server-side application upgrade a client to download the application date, and if the former is larger than the latter, is not updated; if the former is smaller than the latter, then get a list of download files via a dynamic array, start downloading the file.

() Function is implemented by BatchDownload. Upgrade program detects whether the old main activity, if the old main activity is closed; remove the old main program, copy files in the temporary folder to the appropriate location; check the status of the main program, if the state is active, start a new main program.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

private void BatchDownload(object data)

{

this.Invoke(this.activeStateChanger, new object[]{true, false});

try

{

DownloadInstructions instructions = (DownloadInstructions) data;

//批量下载

using(BatchDownloader bDL = new BatchDownloader())

{

bDL.CurrentProgressChanged += new DownloadProgressHandler(this.SingleProgressChanged);

bDL.StateChanged += new DownloadProgressHandler(this.StateChanged);

bDL.FileChanged += new DownloadProgressHandler(bDL_FileChanged);

bDL.TotalProgressChanged += new DownloadProgressHandler(bDL_TotalProgressChanged);

bDL.Download(instructions.URLs, instructions.Destination, (ManualResetEvent) this.cancelEvent);

}

}

catch(Exception ex)

{

ShowErrorMessage(ex);

}

this.Invoke(this.activeStateChanger, new object[]{false, false});

this.labFileName.Text = "";

//更新程序

if(this._Update)

{

//关闭原有的应用程序

this.labDownFile.Text = "正在关闭程序....";

System.Diagnostics.Process[]proc=System.Diagnostics.Process.GetProcessesByName("TIMS");

//关闭原有应用程序的所有进程

foreach(System.Diagnostics.Process pro in proc)

{

pro.Kill();

}

DirectoryInfo theFolder=new DirectoryInfo(Path.GetTempPath()+"JurassicUpdate");

if(theFolder.Exists)

{

foreach(FileInfo theFile in theFolder.GetFiles())

{

//如果临时文件夹下存在与应用程序所在目录下的文件同名的文件,则删除应用程序目录下的文件

if(File.Exists(Application.StartupPath + \\"+Path.GetFileName(theFile.FullName)))

File.Delete(Application.StartupPath + "\\"+Path.GetFileName(theFile.FullName));

//将临时文件夹的文件移到应用程序所在的目录下

File.Move(theFile.FullName,Application.StartupPath + \\"+Path.GetFileName(theFile.FullName));

}

}

//启动安装程序

this.labDownFile.Text = "正在启动程序....";

System.Diagnostics.Process.Start(Application.StartupPath + "\\" + "TIMS.exe");

this.Close();

}

}

Released six original articles · won praise 189 · views 280 000 +

Guess you like

Origin blog.csdn.net/newbie_xymt/article/details/102571848