1

I followed a speech recognition tutorial about opening and closing program. when I execute a command to open MS WORD it does fine but when I try to close the program I get an error message regarding the index was outside the bound of the array. It points to the Procs[0] as being out of bounds.

     public static void killProg(string s)
    {
        System.Diagnostics.Process[] Procs = null;

        try
        {
            Procs = Process.GetProcessesByName(s);
            Process prog = Procs[0];

            if (!prog.HasExited)
            {
                prog.Kill();

            }
        }

        finally
        {
            if (Procs != null)
            {
                foreach (Process p in Procs)
                {
                    p.Dispose();
                }
            }
        }

Can anybody help? I'm very new to using C# and not sure what to do?

Ramonster
  • 11
  • 1

2 Answers2

0

Procs = Process.GetProcessesByName(s); is probably returns 0 elements. Which leads Procs[0]; to throw IndexOutOfRangeException.

Protect your code against the possibility of which you will not find what you were looking for.

Orel Eraki
  • 11,940
  • 3
  • 28
  • 36
0

Apparently the Process.GetProcessesByName(s) call returns an empty array, which means there is no first element (index 0) and hence you get an exception.

You should check if the array is not empty:

Procs = Process.GetProcessesByName(s);
if ( Procs.Length > 0 )
{
   //your code
}
Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91