Console.ReadLine() max length?

Solution 1:

An issue with stack72's answer is that if the code is used in a batch-script the input is no longer line buffered. I found an alternative version at averagecoder.net that keeps the ReadLine call. Note that StreamReader also must have a length argument, since it has a fixed buffer as well.

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

Solution 2:

Without any modifications to the code it will only take a maximum of 256 characters ie; It will allow 254 to be entered and will reserve 2 for CR and LF.

The following method will help to increase the limit:

private 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);
    }

Solution 3:

This is a simplified version of ara's answer and it works for me.

int bufSize = 1024;
Stream inStream = Console.OpenStandardInput(bufSize);
Console.SetIn(new StreamReader(inStream, Console.InputEncoding, false, bufSize));

string line = Console.ReadLine();

Solution 4:

This is a simplified version of Petr Matas' answer. Basically you can specify the buffer size only once as follow :

Console.SetIn(new StreamReader(Console.OpenStandardInput(),
                               Console.InputEncoding,
                               false,
                               bufferSize: 1024));
string line = Console.ReadLine();

Because in the end

Console.OpenStandardInput(int bufferSize)

calls

private static Stream GetStandardFile(int stdHandleName, FileAccess access, int bufferSize)

which doesn't use bufferSize !

Solution 5:

Console.ReadLine() has a 254 character limit.

I found the below single line of code here. That seemed to do the trick.

Console.SetIn(new StreamReader(Console.OpenStandardInput(8192)));