重定向cmd.exe的输入和输出(Redirect input and output for cmd

2019-08-20 04:38发布

我想重定向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");

如何让在这种情况下输出?

Answer 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;
}

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

我建议你使用每个命令的过程来代替。



文章来源: Redirect input and output for cmd.exe