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?
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.
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.
ReadLine() stores strings because this is how it built. But, you can check your input and make casting to the type you would like.
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.
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();
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With