ReadLine Method

StreamReader.ReadLine Method ()


Reads a line of characters from the current stream and returns the data as a string.

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

public override string ReadLine()

Return Value

Type: System.String

The next line from the input stream, or null if the end of the input stream is reached.

Exception Condition

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


An I/O error occurs.

A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r"), or a carriage return immediately followed by a line feed ("\r\n"). The string that is returned does not contain the terminating carriage return or line feed. The returned value is null if the end of the input stream is reached.

This method overrides TextReader.ReadLine.

If the current method throws an OutOfMemoryException, 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. If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. To reset the internal buffer, call the DiscardBufferedData method; however, this method slows performance and should be called only when absolutely necessary.

For a list of common I/O tasks, see Common I/O Tasks.

The following code example reads lines from a file until the end of the file is reached.

using System;
using System.IO;

class Test 

    public static void Main() 
        string path = @"c:\temp\MyTest.txt";
            if (File.Exists(path)) 

            using (StreamWriter sw = new StreamWriter(path)) 
                sw.WriteLine("is some text");
                sw.WriteLine("to test");

            using (StreamReader sr = new StreamReader(path)) 
                while (sr.Peek() >= 0) 
        catch (Exception e) 
            Console.WriteLine("The process failed: {0}", e.ToString());

Universal Windows Platform
Available since 4.5
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top
© 2015 Microsoft