Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
ReadLine Method

Console.ReadLine Method

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

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

[HostProtectionAttribute(SecurityAction.LinkDemand, UI = true)]
public static string ReadLine()

Return Value

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


An I/O error occurred.


There is insufficient memory to allocate a buffer for the returned string.


The number of characters in the next line of characters is greater than Int32.MaxValue.

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.

  • If standard input is redirected to a file, the ReadLine method reads a line of text from a file. For example, the following is a text file named ReadLine1.txt:

    This is the first line.
    This is the second line.
    This is the third line.
    This is the fourth line.

    If the following example can then be compiled to an executable named ReadLine1.exe and run from the command with the syntax

    ReadLine1 < ReadLine1.txt

    to redirect input from the file.

    using System;
    public class Example
       public static void Main()
          Console.WriteLine("About to call Console.ReadLine in a loop.");
          String s;
          int ctr = 0;
          do {
             s = Console.ReadLine();
             Console.WriteLine("Line {0}: {1}", ctr, s);
          } while (s != null);
    // The example displays the following output: 
    //       About to call Console.ReadLine in a loop. 
    //       ---- 
    //       Line 1: This is the first line. 
    //       Line 2: This is the second line. 
    //       Line 3: This is the third line. 
    //       Line 4: This is the fourth line. 
    //       Line 5: 
    //       ---

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 OpenStandardInput(Int32) method.

The ReadLine method executes synchronously. That is, it blocks until a line is read or the Ctrl+Z keyboard combination is pressed. The In property returns a TextReader object that represents the standard input stream and that has both a synchronous TextReader.ReadLine method and an asynchronous TextReader.ReadLineAsync method. However, when used as the console's standard input stream, the TextReader.ReadLineAsync executes synchronously rather than asynchronously and returns a Task<String> only after the read operation has completed.

If this method throws an OutOfMemoryException exception, the reader's position in the underlying Stream object is advanced by the number of characters the method was able to read, but the characters already read into the internal 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 TextReader. If the initial position within the stream is unknown or the stream does not support seeking, the underlying Stream also needs to be reinitialized. To avoid such a situation and to produce robust code, you should use the KeyAvailable property and ReadKey method and store the read characters in a pre-allocated 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 ReadLine method is called in a loop. The following example illustrates this scenario.

using System;

public class Example
   public static void Main()
      string line;
      Console.WriteLine("Enter one or more lines of text (press CTRL+Z to exit):");
      do { 
         Console.Write("   ");
         line = Console.ReadLine();
         if (line != null) 
            Console.WriteLine("      " + line);
      } while (line != null);   
// The following displays possible output from this example: 
//       Enter one or more lines of text (press CTRL+Z to exit): 
//          This is line #1. 
//             This is line #1. 
//          This is line #2 
//             This is line #2 
//          ^Z 
//       >

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: UI. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

The following example requires two command line arguments: the name of an existing text file, and the name of a file to write the output to. It opens the existing text file and redirects the standard input from the keyboard to that file. It also redirects the standard output from the console to the output file. It then uses the Console.ReadLine method to read each line in the file, replaces every sequence of four spaces with a tab character, and uses the Console.WriteLine method to write the result to the output file.

using System;
using System.IO;

public class InsertTabs {
    private const int tabSize = 4;
    private const string usageText = "Usage: INSERTTABS inputfile.txt outputfile.txt";
    public static int Main(string[] args) {
        StreamWriter writer = null;

        if (args.Length < 2) {
            return 1;

        try {
            // Attempt to open output file.
            writer = new StreamWriter(args[1]);
            // Redirect standard output from the console to the output file.
            // Redirect standard input from the console to the input file.
            Console.SetIn(new StreamReader(args[0]));
        catch(IOException e) {
            TextWriter errorWriter = Console.Error;
            return 1;            
        string line;
        while ((line = Console.ReadLine()) != null) {
            string newLine = line.Replace(("").PadRight(tabSize, ' '), "\t");
        // Recover the standard output stream so that a  
        // completion message can be displayed.
        StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
        standardOutput.AutoFlush = true;
        Console.WriteLine("INSERTTABS has completed the processing of {0}.", args[0]);
        return 0;

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8
© 2015 Microsoft