Console IO Redirect in C#

      No Comments on Console IO Redirect in C#

Simple windows forms application that runs “cmd.exe” in hidden console window and redirects input, output and error streams to gui form.

Class CConsoleRedirect.cs has everything you need. Let’s take a quick look at main elements.

Process _shell_process = null; // process for cmd.exe
Stream _shell_reader = null; // process output stream
Stream _shell_writer = null; // process input stream

public DGStr readStringOutputMethod { get; set; } // output text received

_shell_process = new Process(); // create new shell process
_shell_process.StartInfo.FileName = _shell_exe; // start "cmd.exe"
_shell_process.StartInfo.CreateNoWindow = true; // hide console window
_shell_process.StartInfo.UseShellExecute = false; // use system shell
_shell_process.StartInfo.RedirectStandardInput = true; // redirect input stream
_shell_process.StartInfo.RedirectStandardOutput = true; // redirect output stream
_shell_process.Start(); // start process

_shell_reader = _shell_process.StandardOutput.BaseStream; // get output stream
_shell_writer = _shell_process.StandardInput.BaseStream; // get input stream

byte[] _shell_read_output_buffer = new byte[2048]; // read buffer

// begin async read output
private void shellReadOutputBegin() {
  _shell_reader.BeginRead(
  _shell_read_output_buffer,
  0,
  _shell_read_output_buffer.Length,
  new AsyncCallback(shellReadOutputEnd),
  _shell_reader);
}
// end async read output
private void shellReadOutputEnd(IAsyncResult iar) {
  if (_shell_reader == null) return;
  int bytes_read = _shell_reader.EndRead(iar);
  if (bytes_read == 0) {
    return;
  }
  if (readStringOutputMethod != null) {
    string data_string = Encoding.UTF8.GetString(_shell_read_output_buffer, 0, bytes_read);
    readStringOutputMethod(data_string);
  }
  shellReadOutputBegin();
}
// write to input
public void Write(string data) {
  byte[] data_raw = Encoding.UTF8.GetBytes(data);
  _shell_writer.Write(data_raw, 0, data_raw.Length);
  _shell_writer.Flush();
}

That’s it. Have fun.

The Visual Studio 2015 solution source Download.

Leave a Reply