Getting a path of a running process by name

允我心安 提交于 2019-12-04 01:17:36

问题


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);
    }
}

回答1:


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.




回答2:


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

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



回答3:


There are really two approaches you can take.

You can do process by name:

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

or you could do what you do but use linq

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


来源:https://stackoverflow.com/questions/11961137/getting-a-path-of-a-running-process-by-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!