System.Console.ReadLine Method

Reads the next line of characters from the standard input stream.

Syntax

public static string ReadLine ()

Returns

The next line of characters from the input stream, or null if no more lines are available.

Exceptions

TypeReason
System.IO.IOExceptionAn I/O error occurred.
OutOfMemoryExceptionThere is insufficient memory to allocate a buffer for the returned string.

Remarks

A line is defined as a sequence of characters followed by a carriage return (hexadecimal 0x000d), a line feed (hexadecimal 0x000a), or the value of the Environment.NewLine property. The returned string does not contain the terminating character(s). By default, the method reads input from a 256-character input buffer. Because this includes the Environment.NewLine character(s), the method can read lines that contain up to 254 characters. To read longer lines, call the Console.OpenStandardInput(int) method.

If this method throws OutOfMemoryException, the reader's position in the underlying System.IO.Stream is advanced by the number of characters the method was able to read, but the characters already read into the internal Console.ReadLine buffer are discarded. Since the position of the reader in the stream cannot be changed, the characters already read are unrecoverable, and can be accessed only by reinitializing the System.IO.TextReader. If the initial position within the stream is unknown or the stream does not support seeking, the underlying System.IO.Stream also needs to be reinitialized.

To avoid such a situation and produce robust code you should use the Console.Read method and store the read characters in a preallocated buffer.

If the Ctrl+Z character is pressed when the method is reading input from the console, the method returns null. This enables the user to prevent further keyboard input when the Console.ReadLine method is called in a loop. The following example illustrates this scenario.

code reference: System.Console.ReadLine#1

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0