-1

When I trying to get the process name, it work well when the target process is running. But it turn out error with [ System.IndexOutOfRangeException ] if the target process was not running.

    public Int32 GetProcessId(String proc)
    {

        Process[] ProcList;
        ProcList = Process.GetProcessesByName(proc);

        return ProcList[0].Id;

    }

is the return error??

  • 1
    `ProcList` is empty for example. – Dmytro Mukalov Mar 28 '19 at 11:38
  • well clearly if the process isn't running it won't return a result and then the array will be empty. And you can't select an item which doesn't exist, hence the error. So you need to check if the item exists before you try and read it. – ADyson Mar 28 '19 at 11:39

2 Answers2

2

Most likely there is no running process with the string that you are using as a filter. Then the call returns an empty array.

You cannot get an array element 0 from an empty array, that's why you are getting this exception.

You cannot/should not return an Int32 from such a method since there is a chance it will return an empty array, so e.g. 0 would be an erroneous result. I suggest that you change your return to Int32? (nullable integer) and return this:

return ProcList.FirstOrDefault()?.Id;

P.S. Unless you want an exception to happen, which you most likely don't and it is not a good idea to have exceptions control your flow anyway.

Ilya Chernomordik
  • 20,693
  • 15
  • 84
  • 144
0

If the process is not running it wont have an associated PID so ProcList[] would be empty. Then, when you access it in the return statement it throws an exception because there is nothing in that array.

GeersJ
  • 97
  • 1
  • 6