I am trying to send commands to an open cmd.exe process using StandardInput.WriteLine(str)
, however none of the commands seem to be sent. First I open a process, with a global variable p (Process p
).
p = new Process()
{
StartInfo = {
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
FileName = @"cmd.exe",
Arguments = "/C" //blank arguments
}
};
p.Start();
p.WaitForExit();
After, I try to send a command using a simple method, that logs the result in a text box.
private void runcmd(string command)
{
p.StandardInput.WriteLine(command);
var output = p.StandardOutput.ReadToEnd();
TextBox1.Text = output;
}
Right now I am testing it with DIR
, but var output
shows up as null, which results in no output. Is there a better way to send a command to the open cmd.exe process?
I could never get it to work with synchronous reads of stdout without closing stdin, but it does work with async reading for stdout/stderr. No need to pass in /c
, you only do that when passing in a command through the arguments; you are not doing this though, you are sending the command directly to the input.
var p = new Process()
{
StartInfo = {
CreateNoWindow = false,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
FileName = @"cmd.exe"}
};
p.OutputDataReceived += (sender, args1) => Console.WriteLine(args1.Data);
p.ErrorDataReceived += (sender, args1) => Console.WriteLine(args1.Data);
p.Start();
p.BeginOutputReadLine();
p.StandardInput.WriteLine("dir");
p.StandardInput.WriteLine("cd e:");
p.WaitForExit();
Console.WriteLine("Done");