Execute a Process and Fetch its Output

Ever wondered how Visual Studio executes a process - such as a compiler - and displays the text it returns in its own window? It's actually really easy - and here's a simple example as to how.

Shared Function GetProcessText(ByVal process As String, ByVal param As String, ByVal workingDir As String) As String
 Dim p As Process = New Process
 ' this is the name of the process we want to execute
 p.StartInfo.FileName = process
 If Not (workingDir = "") Then
   p.StartInfo.WorkingDirectory = workingDir
 End If
 .StartInfo.Arguments = param
 ' need to set this to false to redirect output
 p.StartInfo.UseShellExecute = False
 p.StartInfo.RedirectStandardOutput = True
 ' start the process
 p.Start
 ' read all the output
 ' here we could just read line by line and display it
 ' in an output window
 Dim output As String = p.StandardOutput.ReadToEnd
 ' wait for the process to terminate
 p.WaitForExit
 Return output
End Function

You might also like...

Comments

James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“C++: an octopus made by nailing extra legs onto a dog.” - Steve Taylor