如何在C#程序结束后将CMD输出内容导出到文本文件?
Solution for Capturing Terminal Output in C#
Core Requirements
- Avoid using
RedirectStandardOutputto preserve real-time updates (liketimeout /t 2) and color changes (likecolor 08) - Capture all terminal content (from both
Console.WriteLineand external processes) only when the program exits - Keep the terminal fully functional during runtime, with export happening only at the end
Approach Using Windows Console API
You can use P/Invoke to interact with the Windows Console API to read the entire screen buffer when your program finishes. Here's a working implementation:
using System; using System.IO; using System.Runtime.InteropServices; class TerminalOutputCapture { [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr GetStdHandle(int nStdHandle); [DllImport("kernel32.dll", SetLastError = true)] static extern bool ReadConsoleOutput( IntPtr hConsoleOutput, [Out] CHAR_INFO[] lpBuffer, COORD dwBufferSize, COORD dwBufferCoord, ref SMALL_RECT lpReadRegion); [StructLayout(LayoutKind.Sequential)] struct COORD { public short X; public short Y; } [StructLayout(LayoutKind.Sequential)] struct SMALL_RECT { public short Left; public short Top; public short Right; public short Bottom; } [StructLayout(LayoutKind.Explicit)] struct CHAR_INFO { [FieldOffset(0)] public char UnicodeChar; [FieldOffset(2)] public short Attributes; } static void Main() { // Your existing program logic here: Console.WriteLine("This line comes from C#'s Console.WriteLine"); System.Diagnostics.Process.Start("cmd.exe", "/c timeout /t 2 && color 08 && echo Output from external process").WaitForExit(); // Trigger capture at program exit SaveConsoleContent("terminal_output.txt"); } static void SaveConsoleContent(string filePath) { IntPtr consoleHandle = GetStdHandle(-11); // Get STD_OUTPUT_HANDLE COORD bufferSize = new COORD { X = Console.WindowWidth, Y = Console.WindowHeight }; SMALL_RECT readArea = new SMALL_RECT { Left = 0, Top = 0, Right = (short)(bufferSize.X - 1), Bottom = (short)(bufferSize.Y - 1) }; CHAR_INFO[] buffer = new CHAR_INFO[bufferSize.X * bufferSize.Y]; if (ReadConsoleOutput(consoleHandle, buffer, bufferSize, new COORD(0,0), ref readArea)) { using (StreamWriter writer = new StreamWriter(filePath)) { for (int y = 0; y < bufferSize.Y; y++) { string line = ""; for (int x = 0; x < bufferSize.X; x++) { line += buffer[y * bufferSize.X + x].UnicodeChar; } writer.WriteLine(line.TrimEnd()); // Remove trailing whitespace } } } else { Console.WriteLine("Failed to capture console output."); } } }
Key Notes
- This code captures everything visible in the console window at exit. To capture the full scrollback buffer, modify it to read the total screen buffer size instead of just the window dimensions.
- The
CHAR_INFOstructure includes color attribute data, so you can extend the code to save color information (e.g., using ANSI escape codes in the output file) if needed.
Critical Insight
Reading the console buffer directly via the Windows API skips output redirection entirely, ensuring real-time visibility of dynamic commands and preserving terminal features like color changes.
内容的提问来源于stack exchange,提问作者Srijan Srivastava
相关产品推荐
相关产品推荐

