Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a path of a running process by name

Tags:

c#

.net-2.0

How can I get a path of a running process by name? For example, I know there is a process named "notepad" running, and I want to get the path of it. How to get the path without looping through all other processes?

Not this way!

using System.Diagnostics;

foreach (Process PPath in Process.GetProcesses())
{
    if (PPath.ProcessName.ToString() == "notepad")
    {
        string fullpath = PPath.MainModule.FileName;
        Console.WriteLine(fullpath);
    }
}
like image 624
User6996 Avatar asked Aug 14 '12 21:08

User6996


People also ask

How do I list a process by name?

Open the terminal window or app. To see only the processes owned by a specific user on Linux run: ps -u {USERNAME} Search for a Linux process by name run: pgrep -u {USERNAME} {processName} Another option to list processes by name is to run either top -U {userName} or htop -u {userName} commands.

How do you find the PID of a running program?

Task Manager can be opened in a number of ways, but the simplest is to select Ctrl+Alt+Delete, and then select Task Manager. In Windows, first click More details to expand the information displayed. From the Processes tab, select Details to see the process ID listed in the PID column.


1 Answers

Try something like this method, which uses the GetProcessesByName method:

public string GetProcessPath(string name)
{
    Process[] processes = Process.GetProcessesByName(name);

    if (processes.Length > 0)
    {
        return processes[0].MainModule.FileName;
    }
    else
    {
        return string.Empty;
    }
}

Keep in mind though, that multiple processes can have the same name, so you still might need to do some digging. I'm just always returning the first one's path here.

like image 55
FishBasketGordo Avatar answered Sep 21 '22 17:09

FishBasketGordo