如何在 C# 中读取另一个进程的命令行参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/504208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 05:55:40  来源:igfitidea点击:

How to read command line arguments of another process in C#?

c#processdiagnostics

提问by Dirk Vollmar

How can I obtain the command line arguments of another process?

如何获取另一个进程的命令行参数?

Using static functions of the System.Diagnostics.Processclass I can obtain a list of running processes, e.g. by name:

使用System.Diagnostics.Process类的静态函数,我可以获得正在运行的进程列表,例如按名称:

Process[] processList = Process.GetProcessesByName(processName);

However, there is no way to access the command line used to start this process. How would one do that?

但是,无法访问用于启动此过程的命令行。那怎么办呢?

采纳答案by xcud

If you did not use the Start method to start a process, the StartInfo property does not reflect the parameters used to start the process. For example, if you use GetProcesses to get an array of processes running on the computer, the StartInfo property of each Process does not contain the original file name or arguments used to start the process. (source: MSDN)

如果未使用 Start 方法启动进程,则 StartInfo 属性不会反映用于启动进程的参数。例如,如果您使用 GetProcesses 获取计算机上运行的进程数组,则每个进程的 StartInfo 属性不包含用于启动进程的原始文件名或参数。(来源:MSDN

Stuart's WMI suggestion is a good one:

Stuart 的 WMI 建议是一个很好的建议:

string wmiQuery = string.Format("select CommandLine from Win32_Process where Name='{0}'", processName);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);
ManagementObjectCollection retObjectCollection = searcher.Get();
foreach (ManagementObject retObject in retObjectCollection)
    Console.WriteLine("[{0}]", retObject["CommandLine"]);

回答by plinth

Process.StartInforeturns a ProcessStartInfoobject that allegedly but not necessarily has the arguments in the Arguments property.

Process.StartInfo返回一个ProcessStartInfo对象,该对象据称但不一定具有 Arguments 属性中的参数。

回答by stuartd

If you're targeting Windows XP or later and you can afford the overhead of WMI, a possibility would be to look up the target process using WMI's WIN32_Process class, which has a CommandLine property.

如果您的目标是 Windows XP 或更高版本,并且您负担得起 WMI 的开销,则可以使用 WMI 的WIN32_Process 类查找目标进程,该类具有 CommandLine 属性。

回答by JMD

Are both projects yours? Could you modify the source for the process you're trying to examine to make it give you its command-line arguments, rather than trying to read them from somewhere outside of that process?

两个项目都是你的吗?您能否修改您尝试检查的进程的源代码,使其为您提供命令行参数,而不是尝试从该进程之外的某个地方读取它们?