.NET API Reference

System.IO.StreamReader Class

The StreamReader class implements a TextReader that reads characters from a byte stream in a particular encoding.

Namespace

System.IO

Assembly

System.Runtime.dll

Inheritance

Object → TextReader → StreamReader

Constructors

SignatureDescription
StreamReader(Stream) Initializes a new instance of the StreamReader class for the specified stream, using UTF-8 encoding and detecting byte order marks.
StreamReader(Stream, Encoding) Initializes a new instance with a specified encoding.
StreamReader(String) Initializes a new instance for the file at the specified path, using UTF-8 encoding.
StreamReader(String, Encoding, bool, int) Initializes with custom buffer size and detection of BOM.

Properties

NameTypeDescription
BaseStreamStreamGets the underlying stream.
CurrentEncodingEncodingGets the encoding in which the current file is being read.
EndOfStreamboolIndicates whether the current position is at the end of the stream.
DiscardBufferedDatavoidClears the internal buffer.

Methods

SignatureDescription
int Peek() Returns the next available character but does not consume it.
int Read() Reads the next character from the input stream and advances the character position.
int Read(char[] buffer, int index, int count) Reads a specified maximum number of characters from the current stream and writes the data to a buffer.
string ReadLine() Reads a line of characters from the current stream and returns the data as a string.
string ReadToEnd() Reads all characters from the current position to the end of the stream.
void Close() Closes the stream and releases any resources associated with the reader.

Example

// Read a text file line by line.
using System;
using System.IO;

class Program
{
    static void Main()
    {
        using (var reader = new StreamReader("example.txt"))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}

See Also