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

如何在C#控制台中粘贴大文本?解决粘贴长度限制问题

C#控制台长字符串粘贴长度受限的解决办法

默认控制台的行输入模式存在长度限制,导致粘贴长字符串时被截断,以下两种方案可解决该问题:

方案1:切换到字符输入模式(Windows平台优先)

通过Win32 API修改控制台输入模式,绕过行长度限制,支持回车结束输入,符合常规操作习惯。

代码实现

using System;
using System.Runtime.InteropServices;
using System.Text;

class Program
{
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr GetStdHandle(int nStdHandle);

    private const int STD_INPUT_HANDLE = -10;
    private const uint ENABLE_LINE_INPUT = 0x0002;
    private const uint ENABLE_ECHO_INPUT = 0x0004;

    static string ReadLongConsoleInput()
    {
        var handle = GetStdHandle(STD_INPUT_HANDLE);
        GetConsoleMode(handle, out uint originalMode);
        
        // 禁用行输入与回显,切换为逐字符读取模式
        SetConsoleMode(handle, originalMode & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT));
        
        var inputBuilder = new StringBuilder();
        try
        {
            Console.WriteLine("请粘贴长字符串,完成后按回车结束:");
            while (true)
            {
                var keyInfo = Console.ReadKey(true);
                if (keyInfo.Key == ConsoleKey.Enter)
                    break;
                
                inputBuilder.Append(keyInfo.KeyChar);
            }
        }
        finally
        {
            // 恢复原始控制台模式
            SetConsoleMode(handle, originalMode);
            Console.WriteLine();
        }
        
        return inputBuilder.ToString();
    }

    static void Main()
    {
        var longInput = ReadLongConsoleInput();
        Console.WriteLine($"读取到的字符串长度:{longInput.Length}");
    }
}

方案2:使用StreamReader读取全输入(跨平台友好)

无需调用系统API,直接读取标准输入的全部内容,结束输入需按Ctrl+Z(Windows)或Ctrl+D(Linux/macOS)。

代码实现

using System;
using System.IO;

class Program
{
    static string ReadLongInputFromStream()
    {
        Console.WriteLine("请粘贴长字符串,完成后按Ctrl+Z(Windows)或Ctrl+D(Linux/macOS)结束:");
        using var reader = new StreamReader(Console.OpenStandardInput());
        return reader.ReadToEnd();
    }

    static void Main()
    {
        var longInput = ReadLongInputFromStream();
        Console.WriteLine($"读取到的字符串长度:{longInput.Length}");
    }
}

注意事项

  • 方案1仅适用于Windows平台,方案2支持所有.NET兼容的操作系统
  • 两种方案均可处理MB级别的长字符串,无硬性长度限制

内容的提问来源于stack exchange,提问作者masternbslay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 07:12:45