C#WPF program realizes automatic version update after opening (. net4.0 or above)

##C# WPF program realizes automatic update of open version
Due to the needs of the project, it is necessary to automatically detect the version and update the version after the local WPF software is started.
Let's share the logic and code of this part of the function realization. It is relatively simple, but it can realize the function.
Program A is the target program (i.e. the program to be updated), and program B is the version update program.
First write A simple A program interface:

Then the B program is invoked in the backend code of the A program.

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            //Obtain the current software version (used to compare whether the software version is updated in program B), program path (used to copy files to this path in program B), program name (used to Kill A in program B)
            var version = Application.ResourceAssembly.GetName().Version.ToString();
            var dirPath = System.IO.Directory.GetCurrentDirectory();
            var exeName = this.GetType().Assembly.Location.Substring(dirPath.Length+1).Split('.');

            //Get the startup program path of B program
            var path = @"C:\Fan021\Code\Practise\VersionUpdate\VersionUpdateTool\VersionUpdateTool\bin\Debug\VersionUpdateTool.exe";
            //Merge parameters into B program
            var para = dirPath+' '+ exeName[0] + ' ' + version;

            //The following code is used to Run the B program
            ProcessStartInfo versionUpdatePrp = new ProcessStartInfo(path, para);
            Process newProcess = new Process();
            newProcess.StartInfo = versionUpdatePrp;
            newProcess.Start();

        }
    }

So far, the A-end program code is completed, and the main version detection and version update are completed by the B program.

B program is also A WPF project. After creating the project, it will be displayed in app The OnStartup method is rewritten in XAML to receive the parameters passed by A program:

   public partial class App : Application
    {
        //Create a static variable to call the daemon
        public static string[] Args= {};

        protected override void OnStartup(StartupEventArgs e)
        {
            if (e.Args != null && e.Args.Count() > 0)
            {
                //Assign the parameters passed from A to the static variable Args created above
                Args = e.Args;
            }
            base.OnStartup(e);
        }
    }

Then simply draw the interface of program B:

In the background constructor of B program, obtain the version number to be updated from the database, XML or other configuration files. The detailed acquisition process is not written here. You can obtain it according to your own needs. The version of A program is 1.0.0.0. Here, in order to trigger version update, the version obtained by simulation is 1.0.0.1.

   public MainWindow()
        {
            InitializeComponent();

            if (App.Args.Count() != 0)
            {
                //Obtain the latest software version from the database or configuration file. The acquisition process is omitted here and only "1.0.0.1" is simulated;
                var newVersion = "1.0.0.1";

                //Whether the comparison version needs to be updated
                if (App.Args[2] != newVersion)
                {
                    //The following is the information displayed on the interface
                    this.Topmost = true;
                    Message.Text += ("New version found:" + newVersion + "\r\n");
                    Message.Text += ("The current software version is:" + App.Args[2] + "\r\n");
                    Message.Text += ("Please confirm whether to update?" + "\r\n");
                }
                else
                {
                    this.Close();
                }

            }
        }

Here's an explanation, app Args this array contains all the parameters passed by A program, app Args [0] corresponds to the dirPath variable in program A and stores the folder path of program A, app Args [1] corresponds to the exeName variable in program A and stores the name of the startup program of program A, app Args [2] corresponds to the version variable in program A and the current version number of program A.

The click event code of the update button in the B program is as follows, and the logic is shown in the notes:

   private void Update_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //The startup program name passed through A will kill the A program
                Process[] processes = Process.GetProcessesByName(App.Args[1]);
                foreach (var item in processes)
                {
                    item.Kill();
                }


                Message.Text += ("Please do not close this program during software update!" + "\r\n");
                Message.Text += ("************************************************************************************" + "\r\n");
                Thread.Sleep(1000);

                //Get the folder path where the latest version of A program is located
                var updateExeDir = @"C:\Fan021\Code\Practise\VersionUpdate\WpfApp1\WpfApp1\bin\Debug";
                var files = Directory.GetFiles(updateExeDir);

                //Copy the files in the folder of the latest version of program A one by one to the folder of the existing version of program A
                //The path of the folder where the existing version of a program is located is also passed by A
                foreach (var item in files)
                {
                    string fName = item.Substring(updateExeDir.Length + 1);
                    File.Copy(System.IO.Path.Combine(updateExeDir, fName), System.IO.Path.Combine(App.Args[0], fName), true);
                }
                Message.Text += ("The software update is complete, please close this program and restart the target program!" + "\r\n");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

The B program code ends here. At this time, run the A program under the A program file, and the B program will pop up and display as follows:


Click Update here. After the update, the interface is as follows. At this time, there is only the interface of program B, and the process of program A has been kill ed:

At this time, looking back at the files in the A program folder, it is found that although the name is still the same, the time has been updated:

Open program A again and find that the "+" sign of the program interface has been changed to the "-" sign of the latest version:

So far, the program version update is completed.

The update here requires the operator to click the "update" button on the interface of program B. there is manual intervention. This is mainly because the user may not need to use the latest version of the program immediately, and may need to use the old version of the software for a period of time.
If this aspect is not considered, you can add the logic under the "update" button directly to the constructor of program B, and add this at the end of the logic Close(), which can realize the real automatic update.

The above codes use VS2017 net 4.0.
Welcome to leave a message to discuss

Reprint please indicate the source, otherwise you will be held accountable!

Keywords: C# .NET WPF

Added by itisprasad on Sun, 20 Feb 2022 00:25:45 +0200