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



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

根据 MSDN on Application.Restart()

如果应用程序在首次执行时最初提供了命令行选项,则重新启动将使用相同的选项再次启动该应用程序。

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

有没有办法在调用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方法查找命令行参数并创建新的命令行参数字符串并将其传递给Arguments startInfo的属性就足够了。GetCommandLineArgs返回的第一项数组是应用程序可执行路径,因此我们忽略了它。以下示例从原始命令行中删除参数/x(如果可用):

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

有关Application.Restart工作原理的更多信息,请查看Application.Restart源代码。

最新更新