How to restart program in C#

By FoxLearn 11/10/2024 1:03:19 PM   54
To restart a program in C#, you can achieve it by launching a new instance of the program and exiting the current instance.

To start the same program instance as current process and close the current process at the same time. Depending on application types, the implementation might be a little different, but the basic idea is same.

For example:

private void RestartProgram()
{
    // Get the current application's executable path
    var exePath = Assembly.GetExecutingAssembly().Location;
    //var exePath = Application.ExecutablePath;  // for WinForms
 
    // Start a new instance of the application
    Process.Start(exePath);
     
    // For Windows Forms app
    Application.Exit();
                 
    // For all Windows application but typically for Console app.
    //Environment.Exit(0);
}

System.Reflection.Assembly.GetEntryAssembly().Location is used to get the path of the currently executing program.

Process.Start(exePath) starts a new instance of the application.

Environment.Exit(0) ends the current process, effectively "restarting" it by launching a fresh instance.

In WinForms applications, you can use `Application.Restart()` to restart the program.

This approach works well for restarting desktop applications, but may not be suitable for ASP.NET applications or services.