Erm's I.T. Girl – Zelna Ellis

Don't fear when Zel is near…

VB.NET – Catch error messages from Process

In previous posts, how to run MySQL scripts and add local users and groups with net command in VB.NET, it did not catch any errors from the child processes running.

In this post, you will see how easy it is to catch those error messages.

Download code (PDF) here.

In this example, it will display message "Process Completed" or the "Error message" in a label on the GUI.

Process

Process

Here is the code snippet:
Private Sub RunTheCommand(ByVal TheCommand As String, ByVal TheArguments As String)
     Try
          Dim proc As New Process
          Dim err As String = ""
          'Clear any messages in the GUI.
          lblError.Text = ""

          proc.StartInfo.FileName = TheCommand
          proc.StartInfo.Arguments = TheArguments

          'StartInfo.UseShellExecute must be False when StartInfo.RedirectStandardError = True.
          'Otherwise when reading the stream from StandardError will throw an exception.
          proc.StartInfo.UseShellExecute = False
          proc.StartInfo.RedirectStandardError = True
          'Don’t show command prompt window.
          proc.StartInfo.CreateNoWindow = True
          'Start process
          proc.Start()
          'Read the error stream (synchronously) first to the end before
          'waiting for the child process to exit – to avoid a deadlock.
          err = proc.StandardError.ReadToEnd
          proc.WaitForExit()
          proc.Close()

          'Display errors on the GUI if any
          If err = "" Then
               lblError.Text = "Process Completed"
          Else
               lblError.Text = err
          End If

     Catch ex As Exception
          MessageBox.Show(Err.Description, "Process Error", _
               MessageBoxButtons.OK, MessageBoxIcon.Error)
     End Try
End Sub

Happy Coding🙂

17 October 2009 - Posted by | .NET & MySQL | , , , ,

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: