【问题标题】:Redirect input and output for cmd.exe重定向 cmd.exe 的输入和输出
【发布时间】:2013-03-30 00:40:39
【问题描述】:

我想将 cmd.exe 输出重定向到某处,当命令为一行时,下面的代码可以工作:

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

但是像 WriteLine() 这样的一系列命令怎么样:

p.StandardInput.WriteLine("cd...");
p.StandardInput.WriteLine("dir");

在这种情况下如何获得输出?

【问题讨论】:

  • 澄清:你想要你的命令的所有输出吗?还是最后一个?连续拨打RunWithRedirect() 已经达到您的目标。
  • 同时,我的命令是串联的。像“cd path”然后“做某事”,我想要所有的输出
  • 连续拨打RunWithRedirect()怎么样?在你的情况下听起来没问题。

标签: c# console cmd stdout stdin


【解决方案1】:

要实现这种行为,您应该使用/k 开关以交互模式运行cmd.exe

问题在于将输入与不同的命令分开。 为此,您可以使用prompt 命令更改标准提示:

prompt --Prompt_C2BCE8F8E2C24403A71CA4B7F7521F5B_F659E9F3F8574A72BE92206596C423D5 

所以现在很容易确定命令输出的结束。

完整代码如下:

public static IEnumerable<string> RunCommands(params string[] commands) {
    var process = new Process {
        StartInfo = new ProcessStartInfo("cmd") {
            UseShellExecute = false,
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            CreateNoWindow = true,
            Arguments = "/k",
        }
    };

    process.Start();

    const string prompt = "--Prompt_C2BCE8F8E2C24403A71CA4B7F7521F5B_F659E9F3F8574A72BE92206596C423D5 ";

    // replacing standard prompt in order to determine end of command output
    process.StandardInput.WriteLine("prompt " + prompt);
    process.StandardInput.Flush();
    process.StandardOutput.ReadLine();
    process.StandardOutput.ReadLine();

    var result = new List<string>();

    try {
        var commandResult = new StringBuilder();

        foreach (var command in commands) {
            process.StandardInput.WriteLine(command);
            process.StandardInput.WriteLine();
            process.StandardInput.Flush();

            process.StandardOutput.ReadLine();

            while (true) {
                var line = process.StandardOutput.ReadLine();

                if (line == prompt) // end of command output
                    break;

                commandResult.AppendLine(line);
            }

            result.Add(commandResult.ToString());

            commandResult.Clear();

        }
    } finally {
        process.Kill();
    }

    return result;
}

它运作良好,但看起来像一个大黑客。

我建议您改为使用每个命令的进程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多