.NET Framework Class Library
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)
Syntax

Visual Basic (Declaration)
Public Overrides Function ReadLine As String
Visual Basic (Usage)
Dim instance As StreamReader
Dim returnValue As String

returnValue = instance.ReadLine()
C#
public override string ReadLine()
Visual C++
public:
virtual String^ ReadLine() override
JScript
public override function ReadLine() : String

Return Value

Type: System..::.String
The next line from the input stream, or nullNothingnullptra null reference (Nothing in Visual Basic) if the end of the input stream is reached.
Exceptions

ExceptionCondition
OutOfMemoryException

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

IOException

An I/O error occurs.

Remarks

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 nullNothingnullptra null reference (Nothing in Visual Basic) if the end of the input stream is reached.

This method overrides 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. 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 StreamReader object. If the initial position within the stream is unknown or the stream does not support seeking, the underlying Stream object also needs to be reinitialized.

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

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

Examples

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

Visual Basic
Imports System
Imports System.IO
Imports System.Text

Public Class Test

    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"

        Try
            If File.Exists(path) Then
                File.Delete(path)
            End If

            Dim sw As StreamWriter = New StreamWriter(path)
            sw.WriteLine("This")
            sw.WriteLine("is some text")
            sw.WriteLine("to test")
            sw.WriteLine("Reading")
            sw.Close()

            Dim sr As StreamReader = New StreamReader(path)

            Do While sr.Peek() >= 0
                Console.WriteLine(sr.ReadLine())
            Loop
            sr.Close()
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class
C#
using System;
using System.IO;

class Test 
{
    
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";
        try 
        {
            if (File.Exists(path)) 
            {
                File.Delete(path);
            }

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

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

int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   try
   {
      if ( File::Exists( path ) )
      {
         File::Delete( path );
      }
      StreamWriter^ sw = gcnew StreamWriter( path );
      try
      {
         sw->WriteLine( "This" );
         sw->WriteLine( "is some text" );
         sw->WriteLine( "to test" );
         sw->WriteLine( "Reading" );
      }
      finally
      {
         delete sw;
      }

      StreamReader^ sr = gcnew StreamReader( path );
      try
      {
         while ( sr->Peek() >= 0 )
         {
            Console::WriteLine( sr->ReadLine() );
         }
      }
      finally
      {
         delete sr;
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }
}
Platforms

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0
See Also

Reference

Other Resources

Tags :


Community Content

mwalkersa
Don't forget the encoding!
Unfortunately, files are usually using some form of encoding, and thus you would be wise to take that into account. Otherwise you might suddenly find out that your simple "read file - trim stuff that needs to be trimmed - write file" program does a lot more than you expected, especially when you're working with non-ascii characters.

using (StreamReader streamReader = new StreamReader(filePath, Encoding.Default <-- Where does this come from?))
{
    while (streamReader.Peek() >= 0)
    {
        fileContents.Add(streamReader.ReadLine());
    }
}

using (StreamWriter streamWriter = new StreamWriter(filePath, false, Encoding.Default))
{
    streamWriter.Write(sbFileContents.ToString());
}

Stanley Roark
Documentation is unclear about what happens at end of a file
If you are reading text from a file, then the definition of "line" that is returned by this method is incomplete because it does not specify correctly what happens at the end of a file that is missing a CR,LF,CR/LF at the end of the file.

The definition of "line" as of 4/25/2008 reads thus:
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 nullNothingnullptra null reference (Nothing in Visual Basic) if the end of the input stream is reached.
Thus a "line" returned is defined by three cases:
1. Characters ending in LF
2. Characters ending in CR
3. Characters ending in CR/LF
I have observed that there is a fourth case, not included, where a "line" is actually returned. That is the case where there is a sequence of characters not followed by a LF, a CR, or a CR/LF, which are the FINAL CHARACTERS in a file. Thus the fourth case that should be included in the correct definition of "line" could read thus:
4. A sequence of characters that occur at the end of a file that is being read, which are not followed by LF, CR, or CR/LF.
Another way to make this definition correct would be to add the specification that a LF is "assumed" to occur at the end of every read file, whether or not the actual linefeed (e.g. encoding of an 8-bit ASCII byte with value 10) is really present or not as the last character of the file content.
Tags : contentbug eof

Stanley Roark
Cool
Thus a "line" is the (next) sequences of characters before one of the following:

1. CR --Carriage Return (ASCII 13)
2. LF --Line Feed (ASCII 10)
3. CR/LF --Line Feed followed immediately by a Carriage Return
4. EOF --The End Of File or Stream Occurring

...no sense succumbing to the convolution of the docs.

Tags :

Page view tracker