Thursday, April 17, 2014

VB.net C# Run a bat file or a DOS command prompt

C# examples => http://csharptest.net/532/using-processstart-to-capture-console-output/

Some are global "m_xxxx" variables. You can add by yourself.

''' <summary>
    ''' Run a bat file or a DOS command
    ''' </summary>
    Public Function ExecTask(ByVal sCmd As String, ByVal sArgs As String) As String
        Dim sResult As String = String.Empty
        Dim oProcess As New Process
        Dim oStartInfo As New ProcessStartInfo
        Dim sAppPath As String = String.Empty
        Dim sCmdFull As String = String.Empty
        Dim sMethod As String = m_sClassName & "." & MethodBase.GetCurrentMethod().Name
        Try
            LogMsg(String.Format("Enter, cmd={0}, args={1}", sCmd, sArgs))
            m_sOutput = New StringBuilder
            sCmdFull = sCmd & " " & sArgs
            LogMsg(String.Format("Enter, full cmd={0}", sCmdFull))
            With oStartInfo
                .Arguments = sArgs
                .FileName = sCmd
                .RedirectStandardError = True
                .RedirectStandardOutput = True
                .UseShellExecute = False
                .WindowStyle = ProcessWindowStyle.Hidden
            End With

            oProcess = Process.Start(oStartInfo)
            AddHandler oProcess.OutputDataReceived, AddressOf OutPutDataReceived 'asynchronously read output to prevent deadlock
            oProcess.BeginOutputReadLine()
            m_sError = oProcess.StandardError.ReadToEnd
            oProcess.WaitForExit()
        Catch ex As Exception
            LogMsg(String.Format("Exception {0}", ex.Message))
            m_sError = ex.Message
            m_ErrorList.Add(sMethod & ex.Message)
        Finally
            LogMsg(String.Format("Standard output={0}", m_sOutput.ToString.Trim))
            LogMsg(String.Format("Standard Error={0}", m_sError))
            oProcess.Close()
            oProcess.Dispose()
        End Try
        If m_sError > String.Empty Then
            'Return sPath & " Error: " & m_sError
            Return " Error: " & m_sError
        Else
            Return m_sOutput.ToString
        End If

    End Function

 '
    ' to get the standard output from command line execution of net use
    '
    Private Sub OutPutDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
        m_sOutput.Append(e.Data)
    End Sub

No comments:

Post a Comment