C# 为什么 Process.GetProcessesByName() 总是为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15923371/
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-10 18:28:28  来源:igfitidea点击:

Why is the Process.GetProcessesByName() always null?

c#

提问by SUT

I try to use program to check the process if it exists.

我尝试使用程序来检查进程是否存在。

using System;
using System.Diagnostics;
using System.ServiceProcess;

namespace ServProInfo
{
    class Program
    {
       public static int IfProcessExist(string processName)
        {
            try
            {
                Process[] targetProcess = Process.GetProcessesByName(processName);
                int proLen = targetProcess.Length;
                if (proLen == 0)
                {
                    Console.WriteLine("The process does NOT exist or has exited...");
                    return 0;
                }
                Console.WriteLine("The process status is: Running");
                return 1;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace + "\r\n" + ex.Source);
                return -1;
            }
        }

        static void Main(string[] args)
        {
            string type = args[0];
            string name = args[1];
            switch (type)
            {
                case "p":
                    IfProcessExist(name);
                    break;
            }  
        }
    }
}

However, the Process[] targetProcess is alway null, even when I set processName as an exist process's name.

但是,Process[] targetProcess 始终为空,即使我将 processName 设置为现有进程的名称。

How could I correct the program?

我怎样才能更正程序?

采纳答案by Tomtom

You can try the following: (works fine for me)

您可以尝试以下操作:(对我来说很好用)

Process[] targetProcess = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(processName));

回答by Tanmay Nehete

try this

尝试这个

System.Diagnostics.Process[] p1 = System.Diagnostics.Process.GetProcesses();
foreach (System.Diagnostics.Process pro in p1)
{
    if ((pro.ProcessName.ToUpper().Contains("Application Nanme")
    {
        //U r Operations
    }
}