Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
Previous Versions
.NET Framework 2.0
System.IO
StreamReader Class
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:

Want more? Here are some additional resources on this topic:

.NET Framework Class Library
StreamReader Class

Implements a TextReader that reads characters from a byte stream in a particular encoding.

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

Visual Basic (Declaration)
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class StreamReader
    Inherits TextReader
Visual Basic (Usage)
Dim instance As StreamReader
C#
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public class StreamReader : TextReader
C++
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public ref class StreamReader : public TextReader
J#
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public class StreamReader extends TextReader
JScript
SerializableAttribute 
ComVisibleAttribute(true) 
public class StreamReader extends TextReader

StreamReader is designed for character input in a particular encoding, whereas the Stream class is designed for byte input and output. Use StreamReader for reading lines of information from a standard text file.

StreamReader defaults to UTF-8 encoding unless specified otherwise, instead of defaulting to the ANSI code page for the current system. UTF-8 handles Unicode characters correctly and provides consistent results on localized versions of the operating system.

By default, a StreamReader is not thread safe. See TextReader.Synchronized for a thread-safe wrapper.

The Read(Char[],Int32,Int32) and Write(Char[],Int32,Int32) method overloads read and write the number of characters specified by the count parameter. These are to be distinguished from BufferedStream.Read and BufferedStream.Write, which read and write the number of bytes specified by the count parameter. Use the BufferedStream methods only for reading and writing an integral number of byte array elements.

NoteNote

When reading from a Stream, it is more efficient to use a buffer that is the same size as the internal buffer of the stream.

For an example of using this class, see the Example section. The following table lists examples of other typical or related I/O tasks.

To do this...

See the example in this topic...

Create a text file.

How to: Write Text to a File

Write to a text file.

How to: Write Text to a File

Read from a text file.

How to: Read Text from a File

Append text to a file.

How to: Open and Append to a Log File

File.AppendText

FileInfo.AppendText

Get the size of a file.

FileInfo.Length

Get the attributes of a file.

File.GetAttributes

Set the attributes of a file.

File.SetAttributes

Determine if a file exists.

File.Exists

Read from a binary file.

How to: Read and Write to a Newly Created Data File

Write to a binary file.

How to: Read and Write to a Newly Created Data File

The following code example uses a StreamReader object to read text from a file.

Visual Basic
Imports System
Imports System.IO

Class Test
    Public Shared Sub Main()
        Try
            ' Create an instance of StreamReader to read from a file.
            Dim sr As StreamReader = New StreamReader("TestFile.txt")
            Dim line As String
            ' Read and display the lines from the file until the end 
            ' of the file is reached.
            Do
                line = sr.ReadLine()
                Console.WriteLine(Line)
            Loop Until line Is Nothing
            sr.Close()
        Catch E As Exception
            ' Let the user know what went wrong.
            Console.WriteLine("The file could not be read:")
            Console.WriteLine(E.Message)
        End Try
    End Sub
End Class
C#
using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        try 
        {
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader("TestFile.txt")) 
            {
                String line;
                // Read and display lines from the file until the end of 
                // the file is reached.
                while ((line = sr.ReadLine()) != null) 
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception e) 
        {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}
C++
using namespace System;
using namespace System::IO;
int main()
{
   try
   {
      // Create an instance of StreamReader to read from a file.
      // The using statement also closes the StreamReader.
      StreamReader^ sr = gcnew StreamReader( "TestFile.txt" );
      try
      {
         String^ line;
         
         // Read and display lines from the file until the end of 
         // the file is reached.
         while ( line = sr->ReadLine() )
         {
            Console::WriteLine( line );
         }
      }
      finally
      {
         if ( sr )
            delete (IDisposable^)sr;
      }
   }
   catch ( Exception^ e ) 
   {
      // Let the user know what went wrong.
      Console::WriteLine( "The file could not be read:" );
      Console::WriteLine( e->Message );
   }
}
J#
import System.*;
import System.IO.*;

class Test
{
    public static void main(String[] args)
    {
        try {            
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            StreamReader sr = new StreamReader("TestFile.txt");
            try {
                String line;
                // Read and display lines from the file until the end of 
                // the file is reached.
                while ((line = sr.ReadLine()) != null) {
                    Console.WriteLine(line);
                }
            }
            finally {
                sr.Dispose();
            }            
        }
        catch (System.Exception e) {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.get_Message());
        }
    } //main
} //Test
System.Object
   System.MarshalByRefObject
     System.IO.TextReader
      System.IO.StreamReader
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
BaseStream.Position Property      Wakazula   |   Edit   |  

WATCH: Performing a get on StreamReader.BaseStream.Position may not return the value you expect.

Debug.WriteLine(StreamReader.BaseStream.Position);

Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2008 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker