【问题标题】:Not able to send commands to cmd.exe process无法向 cmd.exe 进程发送命令
【发布时间】:2016-07-20 21:09:47
【问题描述】:

我正在尝试使用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 显示为空,导致没有输出。有没有更好的方法向打开的 cmd.exe 进程发送命令?

【问题讨论】:

  • 你必须调用p.StandardOutput.ReadToEnd() 之前 p.WaitForExit(),否则会出现死锁。见here。你没有提到死锁,但这可能是你的问题。
  • 尝试摆脱 p.WaitForExit(),问题依旧。
  • Cmd /c 启动然后终止 CMD。

标签: c# cmd process stdout stdin


【解决方案1】:

如果不关闭 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");

【讨论】:

  • 还是什么都没有。另外我需要为多个命令保持进程打开,所以我不能关闭它。
  • @FyreeW 通过同步读取标准输出,无论我尝试什么,我都只能通过关闭标准输入来使其工作。但是对于标准输出的异步读取,一切似乎都可以正常工作。我用异步版本编辑了我的答案。
  • 看到cmd shell弹出,但是没有输出。
  • @FyreeW 你必须摆脱Arguments = "/C"。如果你完全复制并粘贴我的代码,它会起作用,那么你必须稍微向后工作,让它做你想做的事情。
  • 我确保完全使用您上面的代码(刚刚创建了一个新方法)。
猜你喜欢
  • 1970-01-01
  • 2016-11-06
  • 1970-01-01
  • 1970-01-01
  • 2011-08-25
  • 2012-06-26
  • 1970-01-01
  • 2020-09-29
相关资源
最近更新 更多