重定向 cmd.exe 的输入和输出

Redirect input and output for cmd.exe(重定向 cmd.exe 的输入和输出)
本文介绍了重定向 cmd.exe 的输入和输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wanna redirect cmd.exe output somewhere, below code works when the command is a line:

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() 这样的一系列命令怎么样:

But how about a series commands like WriteLine():

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

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

how to get output in this situation?

推荐答案

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

To achieve such behavior you should use /k switch to run cmd.exe in interactive mode.

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

The problem is to separate inputs from different commands. To do this you could change the standard prompt using prompt command:

prompt --Prompt_C2BCE8F8E2C24403A71CA4B7F7521F5B_F659E9F3F8574A72BE92206596C423D5 

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

So now it is pretty easy to determine the end of command output.

完整代码如下:

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

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

It works well but it looks like one big hack.

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

I'd recommend you to use process per command instead.

这篇关于重定向 cmd.exe 的输入和输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)