@bobnoordam

Running a console command and capturing the output

This code sample demonstrates how to execute a console command and capture the output. The VB versions takes the “short route” using the shell command, while the C# version takes the approach of starting a process object, which gives you greater control over the proccess and enables you to pipe the outpout directly into the application. It shouldnt be too hard to convert the C# version into VB.NET, which i leave as a challenge to you

VB.NET Version

' --- Run the command-prompt command "query session" and return
'     the results to the user
Shell(String.Format("cmd /c {0}", "query session > output.txt"), AppWinStyle.NormalFocus, True)
  
Using oInfile As New System.IO.StreamReader("output.txt")
    Dim sContent As String = oInfile.ReadToEnd
    MsgBox(sContent)
End Using
' //

C# Version

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;  // Dont forget to add this one
  
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
  
        private void button1_Click(object sender, EventArgs e)
        {
            // Run the command prompt command "query session" and return the
            // results to the user
            string sCmd = "/c query session";
  
            // Define the process information
            ProcessStartInfo pInfo = new ProcessStartInfo("cmd",sCmd);
            pInfo.RedirectStandardOutput = true;
            pInfo.UseShellExecute = false;
            pInfo.CreateNoWindow = false; // set this to TRUE to supress the standard black window
  
            // Create and run the process
            Process oProc = new Process();
            oProc.StartInfo = pInfo;
            oProc.Start();
  
            string sResult = oProc.StandardOutput.ReadToEnd();
            MessageBox.Show(sResult);
  
        }
  
    }
}