无法将命令发送到cmd.exe进程

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