Redirect input and output for 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 的输入和输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:重定向 cmd.exe 的输入和输出


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01