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()
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With