user1632018 user1632018 - 10 months ago 51 Question

Index out of bounds of array

I am trying to monitor a process that the user has chosen. What I am doing is trying to get the filename from the process name so when the process is not found it can launch it again. Now I don't understand my problem. I am getting the error here:

Dim s As String = ProcessArray(0).MainModule.FileName

The thing I do not understand is that it is returning the filename fine. Can anyone help me pinpoint the issue?

Dim ProcessArray As Process()
ProcessArray = Process.GetProcessesByName(procName)
Dim s As String = ProcessArray(0).MainModule.FileName
Dim f As Process
Dim p As Process() = Process.GetProcessesByName(procName)

For Each f In p
If p.Length > 0 Then
For i As Integer = 0 To p.Length - 1
ProcessID = (p(i).Id)
ProcessID = 0
End If
If ProcessID = 0 Then
BotRunning = False
watchdogbool = True
RunBot(watchdogList, ItemClicked.Text, -1)
End If

Answer Source

The error happens, as the others already said, when there was no process of the given name found. So the only way why s has a valid value when the error occurs is, if you execute your code inside a loop and s have a value from a previous iteration (in which the process still run) when the actual error happens.

Most important is that your code and your description what you want to achieve don't match. Basically if you want to start the process again when your program cannot found it anymore, then I would expect some kind of loop.

I guess you want something like this:

Public Sub WatchProcess(procName As String)
    Dim processArray As Process() = Process.GetProcessesByName(procName)
    ' The process must be running when your program starts. If not, throw an exception
    If processArray.Length = 0 Then Throw New ArgumentException("no such process", "procName")

    Dim fileName As String = processArray(0).MainModule.FileName

    While True ' Looking for the process endlessly. Use other conditions proper for you.
        If Process.GetProcessesByName(procName).Length = 0 Then
            ' The process is not running anymore, start it again!
            ' Do all the other stuff you wanna do (set bool flags etc.)
        End If
        Thread.Sleep(5000) ' Wait 5 seconds until the next check
    End While
End Sub

Important is, that this will block the calling thread forever. So you need to work with multi threading, having one thread calling the method for one procName (if you want to give feedback in an UI or watch multiple processes).

As you said in a comment, you can get a Win32Exception stating that you cannot access a 64 bit process with a 32 bit process. To solve that, start your own program in the same mode as the watched process (force a target CPU under Project settings => Compile => Advanced Compile Options => Target CPU). For more info about that see corresponding other questions like this one.