0

I have a C# application, some times I need to restart my application and after that, I need to run some commands and change some variables of my C# application. I restart my application from this below code:

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

I need to insert some codes here to run after exiting.

DerStarkeBaer
  • 673
  • 10
  • 27
Ahad aghapour
  • 2,323
  • 1
  • 22
  • 33
  • [Command-Line Arguments](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/main-and-command-args/command-line-arguments) – Biesi Grr Nov 29 '19 at 10:36

1 Answers1

4

You can create a flag in application settings and then process it on startup:

//Set a flag on restart
Properties.Settings.Default.IsRestarting = true;
Properties.Settings.Default.Save();
Application.Restart();

...
//Process it on startup (e.g. Main method or Form.Load event for the main form)
if(Properties.Settings.Default.IsRestarting) 
{
    // run some commands and change some variables here
    Properties.Settings.Default.IsRestarting = false;
    Properties.Settings.Default.Save();
}

Alternatively, you can store this flag anywhere you want: file system, registry, database, etc.

You can also, use Process.Start instead of Application.Restart to run another instance of your app. This way you can interact with a new process: send command line arguments, pass messages.

Also, see: Why is Application.Restart() not reliable?

default locale
  • 12,495
  • 13
  • 55
  • 62