Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console.ReadLine() max length?

Tags:

c#

When running a small piece of C# code, when I try to input a long string into Console.ReadLine() it seems to cut off after a couple of lines.

Is there a max length to Console.Readline(), if so is there a way to increase that? enter image description here

like image 723
Kyle Brandt Avatar asked Apr 05 '11 20:04

Kyle Brandt


People also ask

What does the console ReadLine () line do?

The ReadLine method reads a line from the standard input stream. (For the definition of a line, see the paragraph after the following list.) This means that: If the standard input device is the keyboard, the ReadLine method blocks until the user presses the Enter key.

What is the use of console ReadLine () in C#?

The C# readline method is mainly used to read the complete string until the user presses the Enter key or a newline character is found. Using this method, each line from the standard data input stream can be read. It is also used to pause the console so that the user can take a look at the output.

Is console ReadLine always a string?

ReadLine() stores strings because this is how it built. But, you can check your input and make casting to the type you would like.

What is the difference between read () and ReadLine () method?

The only difference between the Read() and ReadLine() is that Console. Read is used to read only single character from the standard output device, while Console. ReadLine is used to read a line or string from the standard output device. Program 1: Example of Console.


2 Answers

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(); 
like image 142
ara Avatar answered Sep 17 '22 06:09

ara


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);     } 
like image 43
stack72 Avatar answered Sep 21 '22 06:09

stack72