C# 按名称获取正在运行的进程的路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11961137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:51:29  来源:igfitidea点击:

Getting a path of a running process by name

c#.net-2.0

提问by hlatif

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?

如何按名称获取正在运行的进程的路径?例如,我知道有一个名为“notepad”的进程正在运行,我想获取它的路径。如何在不循环所有其他进程的情况下获得路径?

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

采纳答案by FishBasketGordo

Try something like this method, which uses the GetProcessesByNamemethod:

尝试使用以下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 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.

但是请记住,多个进程可以具有相同的名称,因此您可能仍然需要进行一些挖掘。我总是在这里返回第一个路径。

回答by Austin Salonen

There is a method GetProcessesByNamethat existed in .Net 2.0:

.Net 2.0 中有一个GetProcessesByName方法:

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

回答by SASS_Shooter

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

或者你可以做你所做的但使用 linq

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