简体   繁体   English

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

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

How can I obtain the command line arguments of another process? 如何获取另一个进程的命令行参数?

Using static functions of the System.Diagnostics.Process class I can obtain a list of running processes, eg 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? 一个人怎么做?

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. 如果您没有使用Start方法来启动进程,则StartInfo属性不会反映用于启动进程的参数。 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. 例如,如果使用GetProcesses获取在计算机上运行的一系列进程,则每个Process的StartInfo属性不包含用于启动该进程的原始文件名或参数。 (source: MSDN ) (来源: 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"]);

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

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

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? 您是否可以为正在尝试检查的过程修改源代码,以使其具有命令行参数,而不是尝试从该过程之外的地方读取它们?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM