无法向 cmd.exe 进程发送命令

Not able to send commands to cmd.exe process

我正在尝试使用 StandardInput.WriteLine(str) 向打开的 cmd.exe 进程发送命令,但是 none 的命令似乎已发送。首先我打开一个进程,有一个全局变量 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();

之后,我尝试使用一种简单的方法发送命令,将结果记录在文本框中。

private void runcmd(string command)
{
    p.StandardInput.WriteLine(command);
    var output = p.StandardOutput.ReadToEnd();
    TextBox1.Text = output;
}

现在我正在用 DIR 测试它,但是 var output 显示为 null,这导致没有输出。有没有更好的方法向打开的 cmd.exe 进程发送命令?

在不关闭 stdin 的情况下,我永远无法让它与 stdout 的同步读取一起工作,但它确实与 stdout/stderr 的异步读取一起工作。不需要传入 /c,你只需要在 通过 参数传入命令时这样做;不过你并没有这样做,你是将命令直接发送到输入。

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");