Pages

Tuesday, March 20, 2012

How to handle error and result in Diagnostics.process


Diagnostics.process provides access to local and remote processes and enables you to start and stop local system processes.
The Process component is a useful tool for starting, stopping, controlling, and monitoring applications. Using the Process component, you can obtain a list of the processes that are running, or you can start a new process. A Process component is used to access system processes
If you start any Process by Diagnostics.process object then to get the error in that process you have to raise ErrorDataReceived event. Below I have written a simple example.


' Create instance of Process class
            Dim m_Process As New Process
            m_Process.StartInfo.FileName = = "cmd.exe"
            m_Process.StartInfo.Arguments = "c:\test.bat"
            '   UseShellExecute should be False for RedirectStandardError and RedirectStandardOutput Properity
            m_Process.StartInfo.UseShellExecute = False
            '   RedirectStandardError has to be true to handle ErrorDataReceived Event.
            m_Process.StartInfo.RedirectStandardError = True
            '   RedirectStandardOutput has to be true to handle OutputDataReceived Event.
            m_Process.StartInfo.RedirectStandardOutput = True
            '   This will hide the console window
            m_Process.StartInfo.CreateNoWindow = True
            '   Start the Process
            m_Process.Start()
            '   Wait for the process to complete
            m_Process.WaitForExit()
            '   Handle error in ErrorHandler function
            AddHandler m_Process.ErrorDataReceived, AddressOf ErrorHandler
            '   Get status of deployment from DataHandler
            AddHandler m_Process.OutputDataReceived, AddressOf DataHandler
            '   Raise the events
            m_Process.BeginErrorReadLine()
            m_Process.BeginOutputReadLine()
            '   Wait for the method to execute
            m_Process.WaitForExit()
            '   Handle the value
            MessageBox.Show(DeploymentError)
            MessageBox.Show(DeploymentStatus)
  Private Sub ErrorHandler(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
        DeploymentError = DeploymentError + e.Data

    End Sub

    Private Sub DataHandler(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
        DeploymentStatus = DeploymentStatus + e.Data
    End Sub

No comments: