kha*_*osh 5 .net c# restart command-line-arguments winforms
我的 winforms(不是 clickonce)应用程序采用只应处理一次的命令行参数。应用程序用于Application.Restart()在对其配置进行特定更改后重新启动自身。
根据MSDN 上的 Application.Restart()
如果您的应用程序在首次执行时最初提供了命令行选项,则 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);
}
Run Code Online (Sandbox Code Playgroud)
此外,如果您需要修改命令行参数,则只需使用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;
Run Code Online (Sandbox Code Playgroud)
有关Application.Restart工作原理的更多信息,请查看Application.Restart 源代码。