C#如何检索通过进程ID

时间:2018-04-12 05:37:28

标签: c#

亲爱的Stackoverflow社区,

我是编程的初学者,我正在构建一个小应用程序。

我遇到以下问题时遇到了困难:

  • 输入:正在运行的进程的ID
  • 输出:执行该过程时执行该命令(如图所示)。

在我的应用程序中,我尝试使用:System.Diagnostics.Process和System.Management.ManagementObject但我找不到要查找的属性,

如果有人向我建议解决这个问题,我将不胜感激。

谢谢。

See pictures

1 个答案:

答案 0 :(得分:0)

您使用System.Management.ManagementObject走在正确的轨道上,并且您正在寻找CommandLine属性。在案例Win32_Process.Handle=6316中,您需要将构造函数传递给对象的WMI路径。例如:

string GetProcessCommandLine(int processId) =>
    System.Management.ManagementObject("Win32_Process.Handle=$processId").CommandLine;

或者,根据https://serverfault.com/questions/696460/given-a-pid-on-windows-how-do-i-find-the-command-line-instruction-that-execute,您可以执行以下WMI查询:

SELECT CommandLine FROM Win32_Process WHERE ProcessID = <your process ID>

您可以使用System.Management.ManagementObjectSearcher从C#完成此操作。在一天结束时,无论如何都将返回与上面相同的ManagementObject(仅填充CommandLine属性)。例如,以下内容应该起作用:

string GetCommandLine(int processId) =>
    System.Management.ManagementObjectSearcher(
        "select CommandLine from Win32_Process where ProcessID = $processId")
    .Get()[0]
    .CommandLine;