user2674867
user2674867

Reputation: 79

Program update code issue

Hey everyone.

I've developed a simple code to auto-update my program. The way it works is:

  1. Program downloads a remote file that has the version string in it. If the version string is bigger than the program's, auto update initiates.

  2. The program downloads the newest version of the program using a remote link with DownloadAsync.

  3. The program creates a new batch file that kills the current app (The program itself), deletes the current program, and renames the new one to the application's name. Then, it runs the new updated application and deletes itself.

However, I'm facing an issue when the batch file is actually executed. Here is my code:

        private void WC_Completed(object sender, AsyncCompletedEventArgs e)
        {

        StringBuilder Batch = new StringBuilder();
        Batch.AppendLine("@echo off");
        Batch.AppendLine("taskkill /IM " + Process.GetCurrentProcess().ProcessName + ".exe /F");
        Batch.AppendLine("ping localhost > nul");
        Batch.AppendLine("del /f " +  (char)34 + Application.ExecutablePath + (char)34);
        Batch.AppendLine("ren " + (char)34 + Application.StartupPath + @"\update.exe" + (char)34 + " " + Process.GetCurrentProcess().ProcessName + ".exe");
        Batch.AppendLine((char)34 + Application.ExecutablePath + (char)34);
        Batch.AppendLine("del %0");

        File.WriteAllText(Application.StartupPath + @"\update.bat", Batch.ToString(), Encoding.Default);
        Process.Start(Application.StartupPath + @"\update.bat");
    }

For some reason, it doen't kill the current application, or it just takes too much, and the whole process is going crazy. It just runs the unupdated app because the renaming doesn't work, which causes a loop.

Can you please point out my error? I'm trying to see what's wrong!

Thank you!

Upvotes: 3

Views: 424

Answers (1)

user2494756
user2494756

Reputation:

There's an easier way to update a program if it consists of one executable file:

  1. Rename a running executable using File.Move to something like my.exe.bak.
  2. Put an updated executable in the place of the old one.
  3. Launch the new copy using Process.Start("my.exe") and exit the old one.
  4. Upon launch test if my.exe.bak exists and try to delete it. You won't succeed first time, but the backup will be deleted eventually.

This way you won't need any .bat trickery.

You can also enchance this algorithm by passing PID (Process ID) of the old instance to the new one through command line arguments and then using Process.GetProcessById(pid).WaitForExit(); to be able to delete my.exe.bak on the first launch and handle update process completion.

Upvotes: 3

Related Questions