This project has moved and is read-only. For the latest updates, please go here.

Updating an exe while executing

Jun 26, 2013 at 5:36 PM
Edited Jun 26, 2013 at 5:38 PM
I added the class "Ourself" that I found in a StackOverflow answer from Orwellophile which renames the currently executing exe.
That code looks like this.

class Ourself
{
    public static string FileName()
    {
        Assembly _objParentAssembly;

        if (Assembly.GetEntryAssembly() == null)
            _objParentAssembly = Assembly.GetCallingAssembly();
        else
            _objParentAssembly = Assembly.GetEntryAssembly();

        if (_objParentAssembly.CodeBase.StartsWith("http://"))
            throw new IOException("Deployed from URL");

        if (File.Exists(_objParentAssembly.Location))
            return _objParentAssembly.Location;
        if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + System.AppDomain.CurrentDomain.FriendlyName))
            return System.AppDomain.CurrentDomain.BaseDirectory + System.AppDomain.CurrentDomain.FriendlyName;
        if (File.Exists(Assembly.GetExecutingAssembly().Location))
            return Assembly.GetExecutingAssembly().Location;

        throw new IOException("Assembly not found");
    }

    public static bool Rename()
    {
        string currentName = FileName();
        string newName = FileName() + ".ori";
        if (File.Exists(newName))
        {
            File.Delete(newName);
        }
        File.Move(currentName, newName);
        return true;
    }
}
Then I changed the OnDownloadComplete() method in DownloadUpdateDialog.cs to the following
    private void OnDownloadComplete(object sender, AsyncCompletedEventArgs e)
    {
        Ourself.Rename();
        string _exePath = Application.ExecutablePath;
        File.Copy(_tempPath, _exePath);

        var processStartInfo = new ProcessStartInfo { FileName = _exePath, UseShellExecute = true };
        Process.Start(processStartInfo);
        if (Application.MessageLoop)
        {
            Application.Exit();
        }
        else
        {
            Environment.Exit(1);
        }
    }
That combination allow me to run a windows form program, update it and have it restart with the newer version.
Feb 18, 2014 at 3:27 PM
  private void OnDownloadComplete(object sender, AsyncCompletedEventArgs e)
    {
        Ourself.Rename();
        string _exePath = Application.ExecutablePath;
        File.Copy(_tempPath, _exePath);
        // If you have a single instance (mutex) of your app 
        Application.Restart();
    }