4 ways to enumerate processes on Windows with C# .NET

A Process object in the System.Diagnostics namespace refers to an operating-system process. This object is the entry point into enumerating the processes currently running on the OS.

This is how you can find the currently active process:

Process current = Process.GetCurrentProcess();
Console.WriteLine(current);

…which will yield the name of the process running this short test code.

It’s probably very rare that you’ll use the above method for anything as it’s not too useful.

You can locate a Process by its ID as follows:

try
{
	Process processById = Process.GetProcessById(7436);
	Console.WriteLine(processById);
}
catch (ArgumentException ae)
{
	Console.WriteLine(ae.Message);
}

I opened the Windows Task Manager and took a process ID from the list. Process ID 7436 at the time of writing this post belonged to Chrome, hence the Console printed “chrome”. The GetProcessById throws an argument exception if there’s no Process with that id: “Process with an Id of 1 is not running”.

There’s an overload of GetProcessById where you can specify the name of the machine in your network where to look for the process.

You can also look for processes by their name:

Process[] chromes = Process.GetProcessesByName("chrome");
foreach (Process process in chromes)
{
	Console.WriteLine("Process name: {0}, ID: {1}", process.ProcessName, process.Id);				
}

I had 4 “chrome” processes running when writing this post with the following ids: 7544, 7436, 6620, 7996. GetProcessesByName also has a machine name overload to check the processes on another machine.

Finally you can enumerate all processes on a machine by the GetProcesses method. The no-args method will enumerate the processes on the local computer. Otherwise provide the computer name in the overloaded version.

try
{
	Process[] allProcessesOnLocalMachine = Process.GetProcesses();
	foreach (Process process in allProcessesOnLocalMachine)
	{
		Console.WriteLine("Process name: {0}, ID: {1}", process.ProcessName, process.Id);
	}
}
catch (Exception ex)
{
	Console.WriteLine(ex.Message);
}

You can view all posts related to Diagnostics here.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.