gpt4 book ai didi

c# - 重定向 cmd.exe 的输入和输出

转载 作者:太空狗 更新时间:2023-10-30 01:21:22 27 4
gpt4 key购买 nike

我想将 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");

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

最佳答案

要实现这种行为,您应该使用 /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;
}

它运行良好,但看起来像是一个大 hack。

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

关于c# - 重定向 cmd.exe 的输入和输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15870516/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com