Getting the path to the running process by name

How can I get the path to the running process by name? For example, I know that there is a process called Notepad, and I want to get its path. How to get a path without going through all the 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);
    }
}
+5
source share
3 answers

Try something like this method that uses the method GetProcessesByName:

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, however, that multiple processes may have the same name, so you may need to perform some operations. I am just returning the first path here.

+8
source

There is a GetProcessesByName method that existed in .Net 2.0:

foreach (Process PPath in Process.GetProcessesByName("notepad"))
{
    string fullpath = PPath.MainModule.FileName;
    Console.WriteLine(fullpath);
}
+2
source

There are two approaches you can take.

You can execute the process by name:

Process result = Process.GetProcessesByName( "Notepad.exe" ).FirstOrDefault( );

or you can do what you do but use linq

Process element = ( from p in Process.GetProcesses()
                    where p.ProcessName == "Notepad.exe"
                    select p ).FirstOrDefault( );
+1
source

All Articles