在 Application.Restart() 之前修改命令行参数

Modify command line arguments before Application.Restart()

我的 winforms(不是 clickonce)应用程序采用的命令行参数应该只处理一次。应用程序使用 Application.Restart() 在对其配置进行特定更改后自行重新启动。

根据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.

这会导致多次处理命令行参数。

有没有办法在调用 Application.Restart() 之前修改(存储的)命令行参数?

您可以使用以下方法在没有原始命令行参数的情况下重新启动您的应用程序:

// 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);
}

此外,如果您需要修改命令行参数,使用 Environment.GetCommandLineArgs method and create new command line argument string and pass it to Arguments 属性 of startInfo 来查找命令行参数就足够了。数组的第一项GetCommandLineArgs returns是应用程序的可执行路径,所以我们忽略它。下面的示例从原始命令行中删除参数 /x(如果可用):

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

有关如何 Application.Restart works, take a look at Application.Restart source code 的更多信息。