How Not To Restart A ClickOnce Application

Normally if you need to restart a WPF application programatically, you would use the following code:

private void Restart() 
{
    System.Diagnostics.Process.Start(
        Application.ResourceAssembly.Location); 
    Application.Current.Shutdown(); 
}

If you have a ClickOnce WPF application, you do not want to do this. In order to understand why, you need to understand how a ClickOnce application is normally launched.

The shortcut you click on in the Start menu is not a normal shortcut to an executable. It is actually an appref-ms file, which defines the entry point and location of the application. When you launch using this file, all the parameters in ApplicationDeployment are correctly initialized, and ApplicationDeployment.IsNetworkDeployed is set to true.

However, if you use the code above, you launch using the application’s entry executable instead of the appref-ms. This will cause ApplicationDeployment.IsNetworkDeployed to be false, and the properties will not be initialized as if they were a ClickOnce deployment.

According to Rob Relyea’s post, Application.Restart() for WPF, you can get the desired functionality with the following code. I have not had a chance to verify that this works as expected, but I will update this post as soon as I do.

UPDATE: I’ve verified that the following code does work properly. Sadly, you will need a reference to the System.Windows.Forms.dll.

private void Restart()
{ 
    // from System.Windows.Forms.dll
    System.Windows.Forms.Application.Restart();
    Application.Current.Shutdown();
}

  • Robert Petz

    As an FYI, this is a great solution as well because it will also preserve your command line arguments. If you were debugging, you can add a debug flag by command line which you can use to relaunch the debugger on startup using ‘Debugger.Launch();’

    • http://blachniet.com/ Brian Lachniet

      That’s awesome, and very useful. Thanks for the tip!

  • superusek

    It does restart application but Properties.Settings are still reset to default… WPF is great but some of most common things are so hard to do.

    • http://blachniet.com/ Brian Lachniet

      Did you save the settings before restarting?

      Properties.Settings.Default.Save();

  • JR

    This works until your application is single-instance. The restart doesn’t actually restart because the app is already running, and then shuts down.