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

标签 c# .net winforms command-line-arguments 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 查找命令行参数就足够了方法并创建新的命令行参数字符串并将其传递给 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 source code .

关于c# - 在 Application.Restart() 之前修改命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37769194/

相关文章:

.net - 在线程中创建 WPF 弹出窗口时出现 "The calling thread must be STA, because many UI components require this"错误

c# - 防止 Size 属性在等于默认值时被序列化

c# - 创建下载加速器

c# - 带有 mysql 数据库的简单登录表单,其用户名将出现在另一个数据库上

c# - 需要帮助在 C# Web 表单应用程序中创建日期选择器

c# - 使用 dataAdapter.Fill() 将 Oracle Date 类型隐式转换为 String

c# - 下载所有数据后是否引发 WebClient.OpenReadCompleted 事件?

c# - 这是一个 if else 语句吗

.net - 确定播放期间的音频来源

c# - 将数据从子窗体发送到父窗体 TextBox