Use C# to Find What Services are Running in a Process

Note: this content originally from http://mygreenpaste.blogspot.com. If you are reading it from some other site, please take the time to visit My Green Paste, Inc. Thank you.

Recently, an individual going by the moniker 'hi' posted a comment to Setting the Priority of a Service Process via Script:

How would I, if I want to, find which services are part of a particular svchost.exe? Can in be done in C#?


I replied via comment, but one has even less control over formatting in comments than one does in the actual blog posting, so I figured I would post the response here as well.


Tasklist.exe with the /svc param can tell you, as can Process Explorer. You can also inspect the registry to determine what services would load with what SVCHOST group (see "Troubleshooting Performance Issues with Automatic Updates" for more details).

As far as C# code, the following requires a reference to System.Management. Invoke the program, passing it the process id of the process you're curious about, and it will output the services running in that process.

using System;
using System.Management;

namespace MyGreenPaste
class Program
static void Main( string[] args )
if( args.GetLength( 0 ) <= 0 )
Console.WriteLine( "Usage: {0} pid",
MainModule.FileName ) );
Console.WriteLine( " where pid is the process id " +
"of a process hosting at least one service" );

ManagementObjectSearcher mos =
new ManagementObjectSearcher( "root\\CIMV2",
string.Format( "SELECT * FROM Win32_Service " +
"where ProcessId={0}", args[0] ) );
foreach( ManagementObject result in mos.Get() )
Console.WriteLine( "{0} -> {1}", result["Name"],
result["DisplayName"] );
catch( ManagementException mex )
Console.WriteLine( "** Error querying WMI:{0}{1}",
System.Environment.NewLine, mex.Message );

No comments: