本文介绍了在Application.Restart()之前修改命令行参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的winforms(不是clickonce)应用程序带有仅应处理一次的命令行参数。应用程序使用 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.

根据

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

Which causes the command line arguments to be processed more than once.

在调用 Application.Restart()之前是否可以修改(存储的)命令行参数?

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

此外,如果您需要修改命令行参数,它足以找到命令行使用 Environment.GetCommandLineArgs 方法并创建新的命令行参数字符串,并将其传递给属性c $ c>。 GetCommandLineArgs 返回的数组的第一项是应用程序可执行路径,因此我们忽略它。下面的示例从原始命令行中删除参数 / x (如果可用):

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;

有关如何起作用,请查看 Application.Restart

这篇关于在Application.Restart()之前修改命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:25