Modify command line arguments before Application.Restart()

若如初见. 提交于 2019-12-13 14:12:07

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/37769194/modify-command-line-arguments-before-application-restart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!