As we all know, we can get information about the processes in the system simply by using the methods provided by the Process
class in the System.Diagnostics
namespace.
For example, you can get all processes by Process.GetProcesses()
and all processes by the specified name by Process.GetProcessesByName()
.
But how do we know if the process is using dotnet or was created by dotnet? Here are three ways to do it.
.Net Core Way
In .Net Core, the CLR provides a simple api to get the processes that use dotnet.
We can install the Microsoft.Diagnostics.NETCore.Client
package via nuget, and use
DiagnosticsClient
class like the example below.
void Main()
{
var processes = DiagnosticsClient.GetPublishedProcesses().Select(GetProcessById);
foreach (var process in processes)
{
Console.WriteLine($"{process.Id,10} {process.ProcessName,-10}");
}
}
private static Process GetProcessById(int processId)
{
try
{
return Process.GetProcessById(processId);
}
catch (ArgumentException)
{
return null;
}
}
We will find that the disadvantage of this method is that only processes that use .Net Core can be found.
Traditional way
We know that a process may contain more than one module, so we can use this feature to determine if the process is using dotnet by checking if the process contains modules from the dotnet runtime.
The most distinctive feature of the modules related to dotnet runtime is that the module name starts with mscor
.
void Main()
{
var processes = Process.GetProcesses();
foreach (var process in processes)
{
if (IsDotNetProcess(process))
{
Console.WriteLine($"{process.Id,10} {process.ProcessName,-10}");
}
}
}
public static bool IsDotNetProcess(Process process)
{
try
{
foreach (ProcessModule module in process.Modules)
{
if (module.ModuleName.StartsWith("mscor", StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
return false;
}
catch
{
return false;
}
}
As you can see, the results include both .Net Core and .Net Framework processes. Note that the detectable processes are related to whether the current process has administrator privileges or not.
Command Line Way
From the command line (including powershell), we can quickly retrieve the processes that are using the specified module via tasklist
.