【发布时间】:2019-05-24 14:34:56
【问题描述】:
我需要从 c# 代码中执行一个 shell 命令,然后将 shell 的输出记录到一个文件中。
我用来执行shell命令的代码是:
using (var process = Process.Start(new ProcessStartInfo
{
FileName = fileName,
Arguments = arguments,
CreateNoWindow = false,
WindowStyle = ProcessWindowStyle.Normal,
RedirectStandardOutput = false,
UseShellExecute = true,
}))
{
// blocking wait for the process to end
process.WaitForExit();
}
我阅读了更改 RedirectStandardOutput = true 和 useShellExecute = false 的其他答案,因此他们可以使用控制台输出
string output = process.StandardOutput.ReadToEnd();
但这不会打开 shell 窗口。
有没有办法将命令输出显示到控制台窗口并获取该输出?
【问题讨论】:
-
看看这个:stackoverflow.com/questions/39358017/…它在过去帮助了我。
-
进程运行了吗?你得到输出了吗?您将输出重定向到一个文件,因此它不会出现在任何窗口中。这与写
dir > list.txt相同。你不会看到输出,它会全部进入文件 -
顺便说一句,在RedirectStandardOutput
By setting RedirectStandardOutput to true to redirect the StandardOutput stream, you can manipulate or suppress the output of a process. For example, you can filter the text, format it differently, or write the output to both the console and a designated log file.中有解释 -
看看这是否有帮助:How do I get output from a command to appear in a control on a Form in real-time?。还有一个示例项目可供您下载并用于测试。
-
我不想重定向标准输出,而只是接受控制台窗口上打印的命令。只需将控制台上的任何内容放入字符串中即可。