How to make the program update automatically and automatically

Source: Internet
Author: User

How to make the program update automatically and automatically

The purpose of auto update is to prevent customers from spending time searching for the latest software. You do not need to go to the developer's website for search. The client's software will automatically find the latest version on the server before the program starts. Compared with the current software version, if the server version is the latest version. The client is automatically downloaded, decompressed, and installed. Of course, a network is required for downloading, and you can follow the prompts to complete the operation. You no longer have to worry about finding the latest version of the software. The following is my general idea and has been implemented:

1. Write a webservice and provide a method to obtain the data of the xml version of the server. (Other file formats are also available. XML is used here)

2. When the WinForm application is started, first access webservice to obtain the version number in the xml of the server, and then obtain the version number in the xml of the client. Compare the two version numbers. if the version number on the server is large, the system prompts you to update the application online.

3. Then the client automatically downloads the RAR package on the network to the specified location on the local machine for automatic decompression. After decompression, use the process to open the decompressed exe file for software installation. Disable the process where the client software is located.

 Code in a web project

First, I will show you the webservice code in my web project. This is simple and there is only one method. The project must be published to IIS.

1.1 code in webservice

[STAThread] static void Main () {Application. enableVisualStyles (); Application. setCompatibleTextRenderingDefault (false); LoadMath ();} private static void LoadMath () {// The server version number string NewEdition = string. empty; // application version string OldEdition = string. empty; try {// obtain the webservice version number myService. webServiceUpdateSoapClient c = new myService. webServiceUpdateSoapClient (); NewEdition = c. getEdition ("clkj _ Ws ");} catch (Exception ex) {MessageBox. show (ex. message);} try {// get the version number stored in xml in the system. XDocument document = XDocument. load ("XMLEdition. xml "); XElement element = document. XPathSelectElement ("Content/Project/Edition"); if (element! = Null) {OldEdition = element. value. toString () ;}} catch (Exception exx) {MessageBox. show (exx. message);} double newE = double. parse (NewEdition); double oldE = double. parse (OldEdition); // compare the two versions to determine whether the application wants to update if (newE> oldE) {// update the program "° DialogResult dr = MessageBox. show ("do you want to update the software for a new version?", "system prompt? ", MessageBoxButtons. OKCancel, MessageBoxIcon. information); if (dr = DialogResult. OK) {// open the download Window Application. run (new DownUpdate ();} else {// if the user cancels, open the initial interface Application. run (new Login ());}}}View Code

 

1.2 code in xml

<? Xml version = "1.0" encoding = "UTF-8"?>

<Content>

<Project id = "p1">

<Name> test </Name>

<Edition> 2.0 </Edition>

</Project>

</Content>

Code in the WinForm Project

The Web project code only has one of the above points, and the focus is on WinForm. In WinForm, you must first add a web reference and copy and use the preceding webservice access address. Next, let's take a step-by-step explanation.

Step 1:

2.1 code in xml

The client code is roughly the same as the xml code for server disconnection. Different versions only use the values in the Edition element.

<? Xml version = "1.0" encoding = "UTF-8"?>

<Content>

<Project id ="P1">

<Name>Test</Name>

<Edition>1.0</Edition>

</Project>

</Content>

2.2 Program. cs code (set the code on the start page)

Add code to the class Program. cs (where to set the start page in WinForm)

 

[STAThread] static void Main () {Application. enableVisualStyles (); Application. setCompatibleTextRenderingDefault (false); LoadMath ();} private static void LoadMath () {// The server version number string NewEdition = string. empty; // application version string OldEdition = string. empty; try {// obtain the webservice version number myService. webServiceUpdateSoapClient c = new myService. webServiceUpdateSoapClient (); NewEdition = c. getEdition ("clkj _ Ws ");} catch (Exception ex) {MessageBox. show (ex. message);} try {// get the version number stored in xml in the system. XDocument document = XDocument. load ("XMLEdition. xml "); XElement element = document. XPathSelectElement ("Content/Project/Edition"); if (element! = Null) {OldEdition = element. value. toString () ;}} catch (Exception exx) {MessageBox. show (exx. message);} double newE = double. parse (NewEdition); double oldE = double. parse (OldEdition); // compare the two versions to determine whether the application wants to update if (newE> oldE) {// update the program "° DialogResult dr = MessageBox. show ("do you want to update the software for a new version?", "system prompt? ", MessageBoxButtons. OKCancel, MessageBoxIcon. information); if (dr = DialogResult. OK) {// open the download Window Application. run (new DownUpdate ();} else {// if the user cancels, open the initial interface Application. run (new Login ());}}}

 

2.3 Main. cs (Main interface after logon) Code

This can be omitted without practical significance.

2.4 DownUpdate. cs (Update page) Code

The interface is displayed as shown in Figure

The automatic update code is as follows (the name of the update button is btnDown and the name of the Install button is btnInstall ):

// Debug directory, used to store the compressed file t string path = Application. startupPath; public DownExe () {InitializeComponent ();} private void DownExe_Load (object sender, EventArgs e) {btnInstall. enabled = false;} // download the file and automatically decompress the file private void btnDown_Click (object sender, EventArgs e) {// automatically download the compressed package, decompress the package, and close the current process, install try {// set the progress bar List <int> resultList = new List <int> (); for (int I = 0; I <100; I ++) {resultList. add (I);} // set Maximum and minimum values of the progress bar this. progressBar1.Maximum = resultList. count; this. progressBar1.Minimum = 0; foreach (int item in resultList) {// download the compressed package System. net. webClient client = new System. net. webClient (); client. downloadFile (@ "http: // 192.168.1.120/File/setup.rar", path + @ "setup.rar"); this. progressBar1.Value ++;} catch {MessageBox. show ("No network or incorrect file address");} if (! Exists () {MessageBox. show ("RAR decompression not supported"); return;} // decompress a 1 try {unCompressRAR (path + "\ setup", path, "setup.rar ", false);} catch (Exception ex) {MessageBox. show (ex. message);} btnInstall. enabled = true; btnDown. enabled = false;} // open the downloaded exe File and disable the private void btnInstall_Click (object sender, EventArgs e) {if (File. exists (path + @ "\ setup \ cboxbeta2.0.0.7.exe") {// open the downloaded exe file Process. Start (path + @ "\ setup \ cboxbeta2.0.0.7.exe"); // close the current Process [] proce = Process. getProcesses (); foreach (Process p in proce) {// Process name of the currently running software if (p. processName = "TestAutoUpdate. vshost ") {p. kill (); break ;}}}} /// <summary> /// extract the file t /// </summary> /// <param name = "unRarPatch"> path of the decompressed file? </Param> /// <param name = "rarPatch"> path of the rarfile </param> /// <param name = "rarName"> rar file name </param> /// <param name = "deleteFlag"> </param> // <returns> </returns> public static string unCompressRAR (string unRarPatch, string rarPatch, string rarName, bool deleteFlag) {try {RegistryKey key = Registry. localMachine. openSubKey (@ "SOFTWARE \ Microsoft \ Windows \ CurrentVersion \ App Paths \ WinRAR.exe"); string str = Key. GetValue (""). ToString (); key. Close (); if (! System. IO. directory. exists (unRarPatch) {System. IO. directory. createDirectory (unRarPatch);} string str2 = "x \" "+ rarName +" \ "\" "+ unRarPatch +" \ "" + "-y "; processStartInfo info = new ProcessStartInfo (); info. fileName = str; info. arguments = str2; info. windowStyle = ProcessWindowStyle. hidden; info. workingDirectory = rarPatch; Process process = new Process (); process. startInfo = info; process. sta Rt (); process. waitForExit (); process. close (); if (deleteFlag & System. IO. file. exists (rarPatch + @ "\" + rarName) {System. IO. file. delete (rarPatch + @ "\" + rarName) ;}} catch (Exception exception) {throw exception;} return unRarPatch ;} /// <summary> /// determine whether RAR automatic decompression is supported /// </summary> /// <returns> </returns> public static bool Exists () {return! String. IsNullOrEmpty (Registry. LocalMachine. OpenSubKey (@ "SOFTWARE \ Microsoft \ Windows \ CurrentVersion \ App Paths \ WinRAR.exe"). GetValue (""). ToString ());}View Code

 

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.