StreamReader Class
Reads characters from a stream in a particular encoding.
Namespace:
Assembly:
mscorlib.dll (in mscorlib.dll)
Inheritance
Object > TextReader > StreamReader
Remarks
The StreamReader
class supports seeking.
StreamReader
is used to read from any stream that can seek and is less than 4 gigabytes in size.
You can use StreamReader
to read from a FileStream
or any other stream that supports seeking.
If the underlying stream is not readable, or if the stream has been closed, StreamReader
throws an ArgumentException
.
Constructors
The StreamReader
class has the following constructors:
Constructor | Description |
---|---|
StreamReader(Stream stream) | Initializes a new instance of the StreamReader class for the specified stream and detects the encoding of the input data. |
StreamReader(Stream stream, bool detectEncodingFromByteOrderMarks) | Initializes a new instance of the StreamReader class for the specified stream, with an option to detect encoding. |
StreamReader(string path) | Initializes a new instance of the StreamReader class for the specified file path. |
StreamReader(string path, System.Text.Encoding encoding) | Initializes a new instance of the StreamReader class for the specified file path and character encoding. |
Methods
The StreamReader
class has the following public methods:
Method | Description |
---|---|
Close() | Closes the underlying stream and the StreamReader object. |
DiscardBufferedData() | Clears the internal buffer. |
Peek() | Returns the next available character, but does not consume it from the input stream. |
Read() | Reads the next character from the input stream and advances the character position by one. |
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, starting at the given index. |
ReadToEnd() | Reads all characters from the current position to the end of the stream and returns them as one string. |
Example
using System;
using System.IO;
using System.Text;
public class Example
{
public static void Main()
{
string filePath = @"C:\temp\mytextfile.txt";
try
{
// Create a file to write to
using (StreamWriter sw = File.CreateText(filePath))
{
sw.WriteLine("This is the first line.");
sw.WriteLine("This is the second line.");
}
// Create a StreamReader to read the file
using (StreamReader sr = new StreamReader(filePath, Encoding.UTF8))
{
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)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}