You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#程序结束后将CMD输出内容导出到文本文件?

Solution for Capturing Terminal Output in C#

Core Requirements

  • Avoid using RedirectStandardOutput to preserve real-time updates (like timeout /t 2) and color changes (like color 08)
  • Capture all terminal content (from both Console.WriteLine and 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_INFO structure 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 01:05:23