简体   繁体   中英

How to read very long input from console in C#?

I need to load veeeery long line from console in C#, up to 65000 chars. Console.ReadLine itself has a limit of 254 chars(+2 for escape sequences), but I can use this:

static string ReadLine()
{
    Stream inputStream = Console.OpenStandardInput(READLINE_BUFFER_SIZE);
    byte[] bytes = new byte[READLINE_BUFFER_SIZE];
    int outputLength = inputStream.Read(bytes, 0, READLINE_BUFFER_SIZE);
    Console.WriteLine(outputLength);
    char[] chars = Encoding.UTF7.GetChars(bytes, 0, outputLength);
    return new string(chars);
}

...to overcome that limit, for up to 8190 chars(+2 for escape sequences) - unfortunately I need to enter WAY bigger line, and when READLINE_BUFFER_SIZE is set to anything bigger than 8192, error "Not enough storage is available to process this command" shows up in VS. Buffer should be set to 65536. I've tried a couple of solutions to do that, yet I'm still learning and none exceeded either 1022 or 8190 chars, how can I increase that limit to 65536? Thanks in advance.

try Console.Read with StringBuilder

        StringBuilder sb =new StringBuilder();
        while (true) {
            char ch = Convert.ToChar(Console.Read());
            sb.Append(ch);
            if (ch=='\n') {
                break;
            }
        }

You have to add following line of code in your main() method:

byte[] inputBuffer = new byte[4096];
                Stream inputStream = Console.OpenStandardInput(inputBuffer.Length);
                Console.SetIn(new StreamReader(inputStream, Console.InputEncoding, false, inputBuffer.Length));

Then you can use Console.ReadLine(); to read long user input.

I agree with Manmay, that seems to work for me, and I also attempt to keep the default stdin so I can restore it afterwards:

        if (dbModelStrPathname == @"con" ||
            dbModelStrPathname == @"con:")
        {
            var stdin = Console.In;

            var inputBuffer = new byte[262144];
            var inputStream = Console.OpenStandardInput(inputBuffer.Length);
            Console.SetIn(new StreamReader(inputStream, Console.InputEncoding, false, inputBuffer.Length));

            dbModelStr = Console.In.ReadLine();

            Console.SetIn(stdin);
        }
        else
        {
            dbModelStr = File.ReadAllText(dbModelStrPathname);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM