我的 C# 代码在终端窗口上打印了很多文本,一些文本是由我通过 C# 运行的其他应用程序打印的
System.Diagnostics
(没有 RedirectStandardOutput
我也不想使用那个 async
东西)并且它打印它自己的文本,一些文本是由 C# Console.WriteLine
函数打印的。
我想将所有文本从上到下保存到一个文本文件中。我不想执行任何文件并存储它的文本,因为所有执行都已经完成并且所有文本都已经打印。我只想在程序结束时将所有这些文本保存到一个文件中。
注意:以下不是我真正的代码(显然),但它看起来有点像这样。
using System.Diagnostics;
Console.WriteLine("Test");
// Create a new process instance
Process process = new Process();
// Configure the process using StartInfo
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = $"/c echo Hello world! & timeout /t 2 & color 08";
// Start the process
process.Start();
// Wait for CMD to finish
process.WaitForExit();
Console.WriteLine("Test1");
/*
---- Save all of that above text that was printed here at the end of the code. ----
*/
我不想使用
RedirectStandardOutput
,因为据我所知,如果我这样做并使用那些process
的东西打印来自async
的东西,首先,它将无法打印实时更新,例如在那个 timeout /t 2
部分,它也无法解释窗口颜色的变化 color 08
。
我想要这样一个系统,它可以让代码正常执行,但是当代码到达末尾时,它将文本导出到文件中,就像现在 Windows 终端的
Export Text
功能的工作方式一样。
这就是你想要的吗?
void Main()
{
var sb = new StringBuilder();
var startInfo = new ProcessStartInfo
{
FileName = "cmd.exe ",
Arguments = $"/c echo Hello world! & timeout /t 2 & color 08",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
using (var process = new Process{StartInfo = startInfo})
{
process.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data);
process.ErrorDataReceived += (sender, args) => sb.AppendLine(args.Data);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
}
Console.WriteLine("start log");
Console.WriteLine(sb.ToString()); //can tace output and save to file
Console.WriteLine("end log");
}
输出:
start log
Hello world!
Waiting for 2 seconds, press a key to continue ...081080
end log