Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify command line arguments before Application.Restart()

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()?

like image 760
khargoosh Avatar asked Oct 19 '22 07:10

khargoosh


1 Answers

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.

like image 149
Reza Aghaei Avatar answered Oct 21 '22 10:10

Reza Aghaei