Stream​Reader Class

Definition

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

[System.Runtime.InteropServices.ComVisible(true)]
public class StreamReader : System.IO.TextReader
Inheritance
Attributes

Inherited Members

System.IO.TextReader

System.MarshalByRefObject

System.Object

Examples

The following example uses an instance of StreamReader to read text from a file. The constructor used in this example is not supported for use in Windows Store Apps.

using namespace System;
using namespace System::IO;
int main()
{
   try
   {
      // Create an instance of StreamReader to read from a file.
      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 );
   }
}
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);
        }
    }
}
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

The following example instantiates a StreamReader object and calls its ReadAsync method to read a file asynchronously.

using System;
using System.IO;
using System.Threading.Tasks;

class Example
{
    public static void Main()
    {
        ReadAndDisplayFilesAsync();
    }

    private async static void ReadAndDisplayFilesAsync()
    {
        String filename = "TestFile1.txt";
        Char[] buffer;
        
        using (var sr = new StreamReader(filename)) {
            buffer = new Char[(int)sr.BaseStream.Length];
            await sr.ReadAsync(buffer, 0, (int)sr.BaseStream.Length);
        }

        Console.WriteLine(new String(buffer));
    }
}
// The example displays the following output:
//       This is the first line of text in a relatively short file.
//       This is the second line.
//       This is the third line.
//       This is the fourth and final line.
Imports System
Imports System.IO
Imports System.Threading.Tasks

Module Example
    Public Sub Main()
        ReadAndDisplayFilesAsync()
    End Sub

    Private Async Sub ReadAndDisplayFilesAsync()
        Dim filename As String = "TestFile1.txt"
        Dim buffer() As Char
        
        Using sr As New StreamReader(filename)
            ReDim buffer(CInt(sr.BaseStream.Length))
            Await sr.ReadAsync(buffer, 0, CInt(sr.BaseStream.Length))
        End Using

        Console.WriteLine(New String(buffer))
    End Sub
End Module
' The example displays the following output:
'       This is the first line of text in a relatively short file.
'       This is the second line.
'       This is the third line.
'       This is the fourth and final line.

Remarks

Note

To view the .NET Framework source code for this type, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

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.

Important

This type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

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. If you get the current character encoding using the CurrentEncoding property, the value is not reliable until after the first Read method, since encoding auto detection is not done until the first call to a Read method.

By default, a StreamReader is not thread safe. See System.IO.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 System.IO.BufferedStream.Read and System.IO.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.

Note

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 a list of common I/O tasks, see Common I/O Tasks.

Constructors

Stream​Reader(​Stream)

Initializes a new instance of the StreamReader class for the specified stream.

Stream​Reader(​String)

Initializes a new instance of the StreamReader class for the specified file name.

Stream​Reader(​Stream, ​Boolean)

Initializes a new instance of the StreamReader class for the specified stream, with the specified byte order mark detection option.

Stream​Reader(​Stream, ​Encoding)

Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding.

Stream​Reader(​String, ​Boolean)

Initializes a new instance of the StreamReader class for the specified file name, with the specified byte order mark detection option.

Stream​Reader(​String, ​Encoding)

Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding.

Stream​Reader(​Stream, ​Encoding, ​Boolean)

Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding and byte order mark detection option.

Stream​Reader(​String, ​Encoding, ​Boolean)

Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding and byte order mark detection option.

Stream​Reader(​Stream, ​Encoding, ​Boolean, ​Int32)

Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.

Stream​Reader(​String, ​Encoding, ​Boolean, ​Int32)

Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding, byte order mark detection option, and buffer size.

Stream​Reader(​Stream, ​Encoding, ​Boolean, ​Int32, ​Boolean)

Initializes a new instance of the StreamReader class for the specified stream based on the specified character encoding, byte order mark detection option, and buffer size, and optionally leaves the stream open.

Fields

Null

A StreamReader object around an empty stream.

Properties

Base​Stream

Returns the underlying stream.

Current​Encoding

Gets the current character encoding that the current StreamReader object is using.

End​Of​Stream

Gets a value that indicates whether the current stream position is at the end of the stream.

Methods

Close()

Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.

Discard​Buffered​Data()

Clears the internal buffer.

Dispose(​Boolean)

Closes the underlying stream, releases the unmanaged resources used by the StreamReader, and optionally releases the managed resources.

Peek()

Returns the next available character but does not consume it.

Read()

Reads the next character from the input stream and advances the character position by one character.

Read(​Char[], ​Int32, ​Int32)

Reads a specified maximum of characters from the current stream into a buffer, beginning at the specified index.

Read​Async(​Char[], ​Int32, ​Int32)

Reads a specified maximum number of characters from the current stream asynchronously and writes the data to a buffer, beginning at the specified index.

Read​Block(​Char[], ​Int32, ​Int32)

Reads a specified maximum number of characters from the current stream and writes the data to a buffer, beginning at the specified index.

Read​Block​Async(​Char[], ​Int32, ​Int32)

Reads a specified maximum number of characters from the current stream asynchronously and writes the data to a buffer, beginning at the specified index.

Read​Line()

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

Read​Line​Async()

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

Read​To​End()

Reads all characters from the current position to the end of the stream.

Read​To​End​Async()

Reads all characters from the current position to the end of the stream asynchronously and returns them as one string.