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

C# 为什么Process.getProcessByName()总是空的?,c#,C#,我尝试使用程序来检查流程是否存在 using System; using System.Diagnostics; using System.ServiceProcess; namespace ServProInfo { class Program { public static int IfProcessExist(string processName) { try {

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

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;
            }  
        }
    }
}
但是,进程[]targetProcess始终为空,即使我将processName设置为现有进程的名称


我怎样才能更正程序

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

试试这个

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

你能举例说明你是如何运行这个程序的吗?比如:你要传递给程序的参数?我猜没有找到进程。您的进程是32位进程,而另一个进程是64位进程?这是最常见的故障模式。如果您尝试使用扩展获取进程,请将其删除,例如尝试获取“svchost”而不是“svchost.exe”,那么您是说您需要删除扩展才能使用
getProcessByName
?我想答案是肯定的。如果我使用Process.getProcessByName(“资源管理器”),我会得到windows资源管理器的任何实例。这是行不通的。指定ToUpper,然后不提供要匹配的大写字符串
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
    }
}