Reputation: 79
Hey everyone.
I've developed a simple code to auto-update my program. The way it works is:
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.
The program downloads the newest version of the program using a remote link with DownloadAsync.
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
Reputation:
There's an easier way to update a program if it consists of one executable file:
my.exe.bak
.Process.Start("my.exe")
and exit the old one.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