I wanna redirect cmd.exe output somewhere, below code works when the command is a line:
Process p = new Process()
{
StartInfo = new ProcessStartInfo("cmd")
{
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
CreateNoWindow = true,
Arguments = String.Format("/c \"{0}\"", command),
}
};
p.OutputDataReceived += (s, e) => Messagebox.Show(e.Data);
p.Start();
p.BeginOutputReadLine();
p.WaitForExit();
But how about a series commands like WriteLine():
p.StandardInput.WriteLine("cd...");
p.StandardInput.WriteLine("dir");
how to get output in this situation?
To achieve such behavior you should use
/k
switch to runcmd.exe
in interactive mode.The problem is to separate inputs from different commands. To do this you could change the standard prompt using
prompt
command:So now it is pretty easy to determine the end of command output.
Here is the complete code:
It works well but it looks like one big hack.
I'd recommend you to use process per command instead.