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

时间:2013-04-10 10:31:05

标签: 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;
            }  
        }
    }
}

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

我怎样才能纠正这个程序?

2 个答案:

答案 0 :(得分:21)

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

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

答案 1 :(得分:1)

试试这个

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