System.IO.StreamReader Class
The StreamReader
class implements a TextReader
that reads characters from a byte stream in a particular encoding. It provides methods for reading a stream of characters, lines, and entire files.
Namespace
System.IO
Assembly
System.Runtime.dll
Syntax
public sealed class StreamReader : TextReader, IDisposable
Constructors
Signature | Description |
---|---|
StreamReader(string path) | Initializes a new instance of StreamReader for the specified file. |
StreamReader(string path, Encoding encoding) | Initializes a new instance of StreamReader for the specified file using the specified encoding. |
StreamReader(Stream stream) | Initializes a new instance of StreamReader based on the specified stream. |
StreamReader(Stream stream, Encoding encoding) | Initializes a new instance of StreamReader based on the specified stream and encoding. |
Properties
Name | Type | Description |
---|---|---|
BaseStream | Stream | Gets the underlying stream. |
CurrentEncoding | Encoding | Gets the encoding in which the current stream is read. |
EndOfStream | bool | Gets a value indicating whether the current position is at the end of the stream. |
LeaveOpen | bool | Gets or sets a value indicating whether to leave the stream open after the StreamReader is disposed. |
Methods
Signature | Description |
---|---|
int Peek() | Returns the next character without consuming it. |
int Read() | Reads the next character from the input stream. |
int Read(char[] buffer, int index, int count) | Reads a block of characters into a buffer. |
string? ReadLine() | Reads a line of characters from the current stream. |
string ReadToEnd() | Reads all characters from the current position to the end of the stream. |
void Close() | Closes the StreamReader and releases any system resources associated with it. |
void DiscardBufferedData() | Clears the internal buffer. |
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);
}
}
}
}