c# - 我可以从 .NET/C# 获取其他进程的命令行参数吗?

标签 c# .net

我有一个项目,其中运行了一个应用程序的多个实例,每个实例都是使用不同的命令行参数启动的。我希望有一种方法可以从其中一个实例中单击一个按钮,然后关闭所有实例并使用相同的命令行参数重新启动它们。

我可以通过 Process.GetProcessesByName() 轻松获取进程本身,但无论何时我这样做,StartInfo.Arguments 属性始终是一个空字符串。看起来该属性可能仅在启动流程之前有效。

This question有一些建议,但它们都是 native 代码,我想直接从 .NET 执行此操作。有什么建议吗?

最佳答案

这使用了所有托管对象,但它确实深入到 WMI 领域:

private static void Main()
{
    foreach (var process in Process.GetProcesses())
    {
        try
        {
            Console.WriteLine(process.GetCommandLine());
        }
        catch (Win32Exception ex) when ((uint)ex.ErrorCode == 0x80004005)
        {
            // Intentionally empty - no security access to the process.
        }
        catch (InvalidOperationException)
        {
            // Intentionally empty - the process exited before getting details.
        }

    }
}

private static string GetCommandLine(this Process process)
{
    using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id))
    using (ManagementObjectCollection objects = searcher.Get())
    {
        return objects.Cast<ManagementBaseObject>().SingleOrDefault()?["CommandLine"]?.ToString();
    }

}

关于c# - 我可以从 .NET/C# 获取其他进程的命令行参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2633628/

相关文章:

.net - 商业软件的视频编码器许可

.net - 从查询中获取表架构

C# 表达式树简单算术

C# 在 switch 语句中定义子类

c# - 如何使用数学来创建更高效​​的代码?

DropDownList 样式的 C# ComboBox,如何设置文本?

c# - 关于 IEnumerable 和 IEnumerator 的问题

.net - FOR XML 要求的无效 XML 标识符

c# - 在最新的 Razor 引擎中找不到 "image/subfolder"下的图像 - MVC.NET

c# - 我可以异步运行同步代码以获得性能吗?