为什么Process.GetProcessesByName()始终为null?

SUT*_*SUT 6 c#

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

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;
            }  
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,即使我将processName设置为存在进程的名称,Process [] targetProcess仍然是null.

我怎么能纠正这个程序?

Tom*_*tom 22

您可以尝试以下方法:(对我来说很好)

Process[] targetProcess = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(processName));
Run Code Online (Sandbox Code Playgroud)

  • 所以你是说你需要删除扩展才能使用`GetProcessesByName`? (6认同)
  • 我认为答案是肯定的。如果我执行 Process.GetProcessesByName("explorer") 我会得到任何 Windows 资源管理器的实例。 (3认同)