6

My winforms (not clickonce) application takes command line arguments that should only be processed once. The application uses Application.Restart() to restart itself after specific changes to its configuration.

According to MSDN on Application.Restart()

If your application was originally supplied command-line options when it first executed, Restart will launch the application again with the same options.

Which causes the command line arguments to be processed more than once.

Is there a way to modify the (stored) command line arguments before calling Application.Restart()?

khargoosh
  • 1,450
  • 15
  • 40
  • 1
    I'm not C# winforms expert, but what about launching the application without the `Application.Restart()`? Try using something like `System.Diagnostics.Process.Start("yourapp.exe");`, and after starting it, you just kill your current process (the one which took arguments). – Alisson Reinaldo Silva Jun 11 '16 at 23:13
  • 2
    Surely following the way that `Application.Restart` works, is more reliable.It first calls private static `ExitInternal` method of `Application` class and then starts the process. – Reza Aghaei Jun 12 '16 at 00:35
  • @RezaAghaei this is an important distinction for applications which, like mine, use resources that cannot overlap between the two processes and must be fully disposed of first. – khargoosh Jun 12 '16 at 05:41

1 Answers1

5

You can restart your application without original command line arguments using such method:

// using System.Diagnostics;
// using System.Windows.Forms;

public static void Restart()
{
    ProcessStartInfo startInfo = Process.GetCurrentProcess().StartInfo;
    startInfo.FileName = Application.ExecutablePath;
    var exit = typeof(Application).GetMethod("ExitInternal",
                        System.Reflection.BindingFlags.NonPublic |
                        System.Reflection.BindingFlags.Static);
    exit.Invoke(null, null);
    Process.Start(startInfo);
}

Also if you need to modify command line arguments, its enough to find command line arguments using Environment.GetCommandLineArgs method and create new command line argument string and pass it to Arguments property of startInfo. The first item of array which GetCommandLineArgs returns is application executable path, so we neglect it. The below example, removes a parameter /x from original command line if available:

var args = Environment.GetCommandLineArgs().Skip(1);
var newArgs = string.Join(" ", args.Where(x => x != @"/x").Select(x => @"""" + x + @""""));
startInfo.Arguments = newArgs;

For more information about how Application.Restart works, take a look at Application.Restart source code.

khargoosh
  • 1,450
  • 15
  • 40
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398