C#如何通过进程ID获取进程运行的 "Command line"(exec.statement)

标签 c#

亲爱的 Stackoverflow 社区,

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

我遇到了以下问题:

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

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

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

谢谢。

See pictures

最佳答案

您在 System.Management.ManagementObject 方面走在了正确的轨道上,并且您正在寻找 CommandLine 属性。您需要向构造函数传递对象的 WMI 路径,在您的情况下为 Win32_Process.Handle=6316。例如:

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>

您可以通过 C# 使用 System.Management.ManagementObjectSearcher 完成此操作.在一天结束时,这将返回与上面相同的 ManagementObject(仅填充了 CommandLine 属性)。例如,像下面这样的东西应该起作用:

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

关于C#如何通过进程ID获取进程运行的 "Command line"(exec.statement),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49788768/

相关文章:

C# Interop 使用特定列的数据获取最后一行

c# - DataGrid 不能输入逗号或点作为值?

c# - 使用 Regex Split 将长字符串拆分为数字和字母组件

c# - 派生类是否应该隐藏从 Comparer<T> 继承的 Default 和 Create 静态成员?

c# - 在施加力之前绘制射弹的点

c# - 取消 Azure 服务总线 QueueClient 长时间运行的接收吗?

c# - 创建新的 Microsoft.CodeAnalysis.CustomWorkspace - 得到 ReflectionTypeLoadException

c# - 如何在不装箱的情况下比较 System.Enum 和枚举(实现)?

c# - always 编译器是否在匿名类型的名称中包含文本 "AnonymousType"?

c# - 仅打印具有来自数据 GridView 的值的行中的列