top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How can I run another application or batch file from my Visual Basic .NET code

+3 votes
462 views
How can I run another application or batch file from my Visual Basic .NET code
posted Mar 1, 2014 by Neeraj Pandey

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

Found it on net: http://blogs.msdn.com/b/vbfaq/archive/2004/05/30/144573.aspx

Suppose you want to run a command line application, open up another Windows program, or even bring up the default web browser or email program... how can you do this from your VB code?

The answer for all of these examples is the same, you can use the classes and methods in System.Diagnostics.Process to accomplish these tasks and more.

Example 1. Running a command line application, without concern for the results:

Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
    System.Diagnostics.Process.Start("C:\listfiles.bat")
End Sub

Example 2. Retrieving the results and waiting until the process stops (running the process synchronously):

Private Sub Button2_Click(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles Button2.Click
    Dim psi As New _
        System.Diagnostics.ProcessStartInfo("C:\listfiles.bat")
    psi.RedirectStandardOutput = True
    psi.WindowStyle = ProcessWindowStyle.Hidden
    psi.UseShellExecute = False
    Dim listFiles As System.Diagnostics.Process
    listFiles = System.Diagnostics.Process.Start(psi)
    Dim myOutput As System.IO.StreamReader _
        = listFiles.StandardOutput
    listFiles.WaitForExit(2000)
    If listFiles.HasExited Then
        Dim output As String = myOutput.ReadToEnd
        Debug.WriteLine(output)
    End If
End Sub

Example 3. Displaying a URL using the default browser on the user's machine:

Private Sub Button3_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button3.Click
    Dim myTargetURL As String = "http://www.duncanmackenzie.net"
    System.Diagnostics.Process.Start(myTargetURL)
End Sub

By the way, you are much better off following the third example for URLs, as opposed to executing IE with the URL as an argument. The code shown here will launch the user's default browser, which may or may not be IE; you are more likely to provide the user with the experience they want and you will be taking advantage of the browser that is most likely to have up-to-date connection information.

answer Mar 3, 2014 by Salil Agrawal
...