VB.NET - How to capture execution output using Shell()?

Asked By Jack Bishop on 31-Aug-04 05:49 PM
Howdy,

I'm trying to capture the output of a command invoked with Shell(). For example, 

Shell("dir c:\", vbMinimizedNoFocus) or, more helpful,

Shell("telnet baz", vbMinimizedNoFocus).

I've attempted playing some redirection games with the local DOS command thinking I can work around some of the resulting limitations but no go. I'm trying to invoke a command on a *nix server and capture its output for further analysis/ investigation. I can invoke a dos command (ergo the "dir c:\" example) to accomplish my goal.

TIA for suggestions and guidance.

Better to use the Process class - Asked By Peter Bromberg on 31-Aug-04 06:49 PM

with the StartInfo methods, than to use the VB.NET "Crutch" classes from the VisualBasic namespaces:

Example (untested code, but you get the idea):

Process process = new Process();
    string FileName="telnet";
    string Arguments = "baz";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.FileName = FileName;
    process.StartInfo.Arguments = Arguments;
    process.StartInfo.WorkingDirectory = WorkingDirectory;
    process.Start(); 
    string output = process.StandardOutput.ReadToEnd();

VB.NET:
Dim process As New Process()
Dim FileName As String = "telnet"
Dim Arguments As String = "baz"
process.StartInfo.UseShellExecute = False
process.StartInfo.RedirectStandardOutput = True
process.StartInfo.RedirectStandardError = True
process.StartInfo.CreateNoWindow = True
process.StartInfo.FileName = FileName
process.StartInfo.Arguments = Arguments
process.StartInfo.WorkingDirectory = WorkingDirectory
process.Start()
Dim output As String = process.StandardOutput.ReadToEnd()