Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, 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?

like image 911
Dirk Vollmar Avatar asked Feb 02 '09 18:02

Dirk Vollmar


People also ask

How do I access command line arguments?

To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. The value of argc should be non negative. argv(ARGument Vector) is array of character pointers listing all the arguments.

How do I pass a command line argument to a program?

If you want to pass command line arguments then you will have to define the main() function with two arguments. The first argument defines the number of command line arguments and the second argument is the list of command line arguments.

Can you pass command line arguments?

It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments and many times they are important for your program especially when you want to control your program from outside instead of hard coding those values inside the code.


1 Answers

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"]); 
like image 115
xcud Avatar answered Sep 20 '22 21:09

xcud