[c#] How do I restart my C# WinForm Application?

Developing a C# .NET 2.0 WinForm Application. Need the application to close and restart itself.

Application.Restart();

The above method has proven to be unreliable.

What is a better way to restart the application?

This question is related to c# .net

The answer is


If you are in main app form try to use

System.Diagnostics.Process.Start( Application.ExecutablePath); // to start new instance of application
this.Close(); //to turn off current app

public static void appReloader()
    {
        //Start a new instance of the current program
        Process.Start(Application.ExecutablePath);

        //close the current application process
        Process.GetCurrentProcess().Kill();
    }

Application.ExecutablePath returns your aplication .exe file path Please follow the order of calls. You might want to place it in a try-catch clause.


You could enclose your code inside a function and when restart is needed you can just call the function.


I fear that restarting the entire application using Process is approaching your problem in the wrong way.

An easier way is to modify the Program.cs file to restart:

    static bool restart = true; // A variable that is accessible from program
    static int restartCount = 0; // Count the number of restarts
    static int maxRestarts = 3;  // Maximum restarts before quitting the program

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        while (restart && restartCount < maxRestarts)
        {
           restart = false; // if you like.. the program can set it to true again
           restartCount++;  // mark another restart,
                            // if you want to limit the number of restarts
                            // this is useful if your program is crashing on 
                            // startup and cannot close normally as it will avoid
                            // a potential infinite loop

           try {
              Application.Run(new YourMainForm());
           }
           catch {  // Application has crashed
              restart = true;
           }
        }
    }

You are forgetting the command-line options/parameters that were passed in to your currently running instance. If you don't pass those in, you are not doing a real restart. Set the Process.StartInfo with a clone of your process' parameters, then do a start.

For example, if your process was started as myexe -f -nosplash myfile.txt, your method would only execute myexe without all those flags and parameters.


I wanted the new application start up after the old one shuts down.

Using process.WaitForExit() to wait for your own process to shutdown makes no sense. It will always time out.

So, my approach is to use Application.Exit() then wait, but allow events to be processed, for a period of time. Then start a new application with the same arguments as the old.

static void restartApp() {
    string commandLineArgs = getCommandLineArgs();
    string exePath = Application.ExecutablePath;
    try {
        Application.Exit();
        wait_allowingEvents( 1000 );
    } catch( ArgumentException ex ) {
        throw;
    }
    Process.Start( exePath, commandLineArgs );
}

static string getCommandLineArgs() {
    Queue<string> args = new Queue<string>( Environment.GetCommandLineArgs() );
    args.Dequeue(); // args[0] is always exe path/filename
    return string.Join( " ", args.ToArray() );
}

static void wait_allowingEvents( int durationMS ) {
    DateTime start = DateTime.Now;
    do {
        Application.DoEvents();
    } while( start.Subtract( DateTime.Now ).TotalMilliseconds > durationMS );
}

I had the same exact problem and I too had a requirement to prevent duplicate instances - I propose an alternative solution to the one HiredMind is proposing (which will work fine).

What I am doing is starting the new process with the processId of the old process (the one that triggers the restart) as a cmd line argument:

// Shut down the current app instance.
Application.Exit();

// Restart the app passing "/restart [processId]" as cmd line args
Process.Start(Application.ExecutablePath, "/restart" + Process.GetCurrentProcess().Id);

Then when the new app starts I first parse the cm line args and check if the restart flag is there with a processId, then wait for that process to Exit:

if (_isRestart)
{
   try
   {
      // get old process and wait UP TO 5 secs then give up!
      Process oldProcess = Process.GetProcessById(_restartProcessId);
      oldProcess.WaitForExit(5000);
   }
   catch (Exception ex)
   { 
      // the process did not exist - probably already closed!
      //TODO: --> LOG
   }
}

I am obviously not showing all the safety checks that I have in place etc.

Even if not ideal - I find this a valid alternative so that you don't have to have in place a separate app just to handle restart.


The problem of using Application.Restart() is, that it starts a new process but the "old" one is still remaining. Therefor I decided to Kill the old process by using the following code snippet:

            if(Condition){
            Application.Restart();
            Process.GetCurrentProcess().Kill();
            }

And it works proper good. In my case MATLAB and a C# Application are sharing the same SQLite database. If MATLAB is using the database, the Form-App should restart (+Countdown) again, until MATLAB reset its busy bit in the database. (Just for side information)


You could also use Restarter.

Restarter is an application that automatically monitor and restarts crashed or hung programs and applications. It was originally developed to monitor and restart game servers, but it will do the job for any console or form based program or application


I use the following and it does exactly what you are looking for:

ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
UpdateCheckInfo info = null;
info = ad.CheckForDetailedUpdate();
if (info.IsUpdateRequired)
{
    ad.UpdateAsync(); // I like the update dialog
    MessageBox.Show("Application was upgraded and will now restart.");
    Environment.Exit(0);
}

I might be late to the party but here is my simple solution and it works like a charm with every application I have:

        try
        {
            //run the program again and close this one
            Process.Start(Application.StartupPath + "\\blabla.exe"); 
            //or you can use Application.ExecutablePath

            //close this one
            Process.GetCurrentProcess().Kill();
        }
        catch
        { }

It's simple, you just need to call the Application.Restart() method, this will invoke your application to be restarted. You must also exit from the local environment with an error code:

Application.Restart();
Environment.Exit(int errorcode);
   

You can create an enumeration of error codes so that you application will exit efficeintly.
Another method is to just exit from the application and start the process using the executable path:

Application.Exit();
System.Diagnostics.Process.Start(Application.ExecutablePath);

I had a similar problem, but mine was related to unmanageable memory leak that I couldn't find on an app that has to run 24/7. With the customer I agreed that safe time to restart the app was 03:00AM if the memory consumption was over the defined value.

I tried Application.Restart, but since it seems to use some mechanism that starts new instance while it is already running, I went for another scheme. I used the trick that file system handles persist until process that created them dies. So, from The Application, i dropped the file to the disk, and didn't Dispose() the handle. I used the file to send 'myself' executable and starting directory also (to add flexibility).

Code:

_restartInProgress = true;
string dropFilename = Path.Combine(Application.StartupPath, "restart.dat");
StreamWriter sw = new StreamWriter(new FileStream(dropFilename, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite));
sw.WriteLine(Application.ExecutablePath);
sw.WriteLine(Application.StartupPath);
sw.Flush();
Process.Start(new ProcessStartInfo
{
    FileName = Path.Combine(Application.StartupPath, "VideoPhill.Restarter.exe"),
    WorkingDirectory = Application.StartupPath,
    Arguments = string.Format("\"{0}\"", dropFilename)
});
Close();

Close() at the end would initiate app shutdown, and file handle I used for StreamWriter here would be held open until process really dies. Then...

Restarter.exe comes into action. It TRIES to read the file in exclusive mode, preventing it to gain access until main app wasn't dead, then starts main app, deletes the file and exists. I guess that it can't be simpler:

static void Main(string[] args)
{
    string filename = args[0];
    DateTime start = DateTime.Now;
    bool done = false;
    while ((DateTime.Now - start).TotalSeconds < 30 && !done)
    {
        try
        {
            StreamReader sr = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite));
            string[] runData = new string[2];
            runData[0] = sr.ReadLine();
            runData[1] = sr.ReadLine();
            Thread.Sleep(1000);
            Process.Start(new ProcessStartInfo { FileName = runData[0], WorkingDirectory = runData[1] });
            sr.Dispose();
            File.Delete(filename);
            done = true;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Thread.Sleep(1000);
    }
}

How about create a bat file, run the batch file before closing, and then close the current instance.

The batch file does this:

  1. wait in a loop to check whether the process has exited.
  2. start the process.

Take for instance an application that:

  1. While application is not registered; (upon start) the application should prompt the user to register the application and create a login account.

  2. Once registration is submitted and login credentials are created; the application should restart, check for registration and prompt the user to login with the inserted credentials (so the user can access to all the application features).

Problem: By building and launching the application from Visual Studio; any of the 4 alternatives bellow will fail to accomplish the tasks required.

/*
 * Note(s):
 * Take into consideration that the lines bellow don't represent a code block.
 * They are just a representation of possibilities,
 * that can be used to restart the application.
 */

Application.Restart();
Application.Exit();
Environment.Exit(int errorCode);
Process.GetCurrentProcess().Kill();

What happens is: After creating the Registration, Login and calling Application.Restart(); the application will (strangely) reopen the Registration Form and skip data in a Database (even though the resource is set to "Copy if Newer").

Solution: Batch Building the application was (for me) a proof that any of the lines above were actually working as expected. Just not when building and running the application with Visual Studio.

In first place I'd try batch building the application; run it outside Visual Studio and check if Application.Restart() actually works as expected.

Also Check further Info regarding this thread subject: How do I restart my C# WinForm Application?


Start/Exit Method

// Get the parameters/arguments passed to program if any
string arguments = string.Empty;
string[] args = Environment.GetCommandLineArgs();
for (int i = 1; i < args.Length; i++) // args[0] is always exe path/filename
    arguments += args[i] + " ";

// Restart current application, with same arguments/parameters
Application.Exit();
System.Diagnostics.Process.Start(Application.ExecutablePath, arguments);

This seems to work better than Application.Restart();

Not sure how this handles if your program protects against multiple instance. My guess is you would be better off launching a second .exe which pauses and then starts your main application for you.


A much simpler approach that worked for me is:

Application.Restart();
Environment.Exit(0);

This preserves the command-line arguments and works despite event handlers that would normally prevent the application from closing.

The Restart() call tries to exit, starts a new instance anyway and returns. The Exit() call then terminates the process without giving any event handlers a chance to run. There is a very brief period in which both processes are running, which is not a problem in my case, but maybe in other cases.

The exit code 0 in Environment.Exit(0); specifies a clean shutdown. You can also exit with 1 to specify an error occurred.


for using As logout you need to terminate all app from Ram Cache so close The Application first and then Rerun it

//on clicking Logout Button

foreach(Form frm in Application.OpenForms.Cast<Form>().ToList())
        {
            frm.Close();
        }
System.Diagnostics.Process.Start(Application.ExecutablePath);

I figured an another solution out, perhaps anyone can use it, too.

string batchContent = "/c \"@ECHO OFF & timeout /t 6 > nul & start \"\" \"$[APPPATH]$\" & exit\"";
batchContent = batchContent.Replace("$[APPPATH]$", Application.ExecutablePath);
Process.Start("cmd", batchContent);
Application.Exit();

Code is simplified so take care of Exceptions and stuff ;)


Here's my 2 cents:

The sequence Start New Instance->Close Current Instance should work even for the applications that don't allow running multiple copies simultaneously as in this case the new instance may be passed a command-line argument which will indicate that there is a restart in progress so checking for other instances running will not be necessary. Waiting for the first instance to actually finish my be implemented too if it's absolutely imperative that no two intstances are running in parallel.


Try this code:

bool appNotRestarted = true;

This code must also be in the function:

if (appNotRestarted == true) {
    appNotRestarted = false;
    Application.Restart();
    Application.ExitThread();
}