Jonathan Schuster Jonathan Schuster - 26 days ago 12
C# Question

Can I get command line arguments of other processes from .NET/C#?

I have a project where I have multiple instances of an app running, each of which was started with different command line arguments. I'd like to have a way to click a button from one of those instances which then shuts down all of the instances and starts them back up again with the same command line arguments.

I can get the processes themselves easily enough through

Process.GetProcessesByName()
, but whenever I do, the
StartInfo.Arguments
property is always an empty string. It looks like maybe that property is only valid before starting a process.

This question had some suggestions, but they're all in native code, and I'd like to do this directly from .NET. Any suggestions?

Answer

This is using all managed objects, but it does dip down into the WMI realm:

private static void Main()
{
    foreach (var process in Process.GetProcesses())
    {
        try
        {
            Console.WriteLine(process.GetCommandLine());
        }
        catch (Win32Exception ex) when ((uint)ex.ErrorCode == 0x80004005)
        {
            // Intentionally empty.
        }
    }
}

private static string GetCommandLine(this Process process)
{
    var commandLine = new StringBuilder(process.MainModule.FileName);

    commandLine.Append(" ");
    using (var searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id))
    {
        foreach (var @object in searcher.Get())
        {
            commandLine.Append(@object["CommandLine"]);
            commandLine.Append(" ");
        }
    }

    return commandLine.ToString();
}
Comments