views:

3186

answers:

4

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, e.g. by name:

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?

+1  A: 

Process.StartInfo returns a ProcessStartInfo object that allegedly but not necessarily has the arguments in the Arguments property.

plinth
It hasn't in my case :( Could be that this only works if the other process is hosted in the CLR.
0xA3
In fact, the Arguments property is only set if the process was started from a managed process using a ProcessStartInfo object.
0xA3
+2  A: 

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.

Stuart Dunkeld
A: 

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?

JMD
Nope, the other process is Microsoft's msiexec
0xA3
+12  A: 

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)

Stuart's WMI suggestion is a good one:

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"]);
xcud
Thanks to you and Stuart, I am using your sample code now.
0xA3
P.S.: And welcome to SO :)
0xA3
Thanks. I've just realized (too late) that stackoverflow is addictive.
xcud
You should dispose the objects.
SLaks
Thanks for the code. Cleaned up version here- http://skysanders.net/subtext/archive/2010/04/11/using-wmi-to-fetch-the-command-line-that-started-all.aspx
Sky Sanders