Codelog

foreach(Snippet aSnippet in CodeLog){ aSnippet.GetSolution(); }

Accessing Command Prompt from C#

without comments

Recently, I wanted to write a program in c# that should start the command prompt in the background (it should not show the cmd window), give inputs from my C# program and get the results redirected back to my C# application. I was googling around a bit and then came up with a solution.

Its damn simple. Usually to start any process from C# applications, we use the Process object. The process object has two properties called StandardInput and StandardOutput. These properties will allow the C# application to get the input stream of the process that needs to be started. So to mock inputs and outputs, we need to do the following,

Process aProcess = new Process();
ProcessStartInfo aStartInfo = new ProcessStartInfo();
aStartInfo.FileName = Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\cmd.exe";
aProcess.StartInfo = aStartInfo;
aProcess.StandardInput.WriteLine("dir");  //will open a cmd process and feed the command "dir" to it

By this way you could give inputs to a process that you start from C#. What if you wanna see output of the cmd prompt in your own prompt ?? For this we use the StandardOutput property. But there is yet another simple way to get the output from the command prompt. This is done by subscribing for the event, OutputDataReceived.

aProcess.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived);
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
  textBox1.AppendText(e.Data);
  textBox1.AppendText(Environment.NewLine);
}

Note: These ways are possible only if,

aProcess.RedirectStandardOutput = true;
aProcess.UseShellExecute = false;
aProcess.BeginOutputReadLine();

are set to the mentioned values. BeginOutputReadLine method will start async read operations from the C# application stream instead of the standard input devices. So next time you wanna clone a command prompt, start the cmd process and give your own look and feel to it.

Written by sudarsanyes

August 31st, 2009 at 5:44 pm

Leave a Reply