Interacting with Cmd.exe

A

Andreas Schmid

Hi,

I tried to launch Cmd.exe using System.Diagnostics and
interact with it - issue commands and read their output.
However, I only seem to be able to issue one command
since I have to call Process.StandardInput.Close() before
I can call Process.StandardOutput.ReadToEnd() - and I
cannot use the StandardInput thereafter.

Here is the code:

using System;
using System.Diagnostics;

public static void Main()
{
Process cmd = new Process();

cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput =
true;
cmd.StartInfo.RedirectStandardOutput =
true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;

cmd.Start();

/* execute "dir" */

cmd.StandardInput.WriteLine("dir");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
Console.WriteLine
(cmd.StandardOutput.ReadToEnd());

/* execute "ipconfig" does not work:
input stream already closed */

cmd.StandardInput.WriteLine("ipconfig");
cmd.StandardInput.Flush();

cmd.StandardInput.Close();
Console.WriteLine
(cmd.StandardOutput.ReadToEnd());

cmd.Close();
}
 
G

Guest

Hi Andreas,

You can get around this by using the ProcessStartInfo class to assign the
Process different things to do. Once this has been done then you can assign
the ProcessStartInfo to the Process before you execute. This way you can
then clear out the ProcessStartInfo, plug in new info and then run the
process. I have posted a sample for you below.

I hope this helps.
---------------------------
string myInput, myArgs;
Console.WriteLine("Input Command:");
myInput = Console.ReadLine();
Console.WriteLine("Input Argument(s): ");
myArgs = Console.ReadLine();
ProcessStartInfo pi = new ProcessStartInfo();
pi.FileName = myInput;
pi.Arguments = myArgs;
pi.UseShellExecute = false;
pi.RedirectStandardOutput = true;
Process p = new Process();
p.StartInfo = pi;
p.Start();
Console.WriteLine(p.StandardOutput.ReadToEnd());

myInput = "";
myArgs = "";

Console.WriteLine("Input Command:");
myInput = Console.ReadLine();
Console.WriteLine("Input Argument(s): ");
myArgs = Console.ReadLine();


pi.FileName = myInput;
pi.Arguments = myArgs;
p.StartInfo = pi;
p.Start();
Console.WriteLine(p.StandardOutput.ReadToEnd());
 
G

Guest

Hi Brian,

Thanks for your answer.

Seems you are re-starting the process with a different
command. I need, however, to use the same command
(cmd.exe) - since certain .bat files I plan to run in the
launched shell (cmd.exe) modify the %PATH% variable.

-Andreas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top