Classes StreamReader and StreamWriter. Working with text files. Constructors of StreamReader class
Contents
- 1. Classes StreamReader, StreamWriter. The purpose
- 2. Overview of methods and properties of the StreamReader class
- 3. Constructors of StreamReader class. Create a stream associated with a text file
- 4. Using the using() statement when creating an input stream
- Related topics
Search other websites:
1. Classes StreamReader, StreamWriter. The purpose
The StreamReader and StreamWriter classes are used to work with streams of character data. The greatest use of classes is working with text files.
The StreamReader class is used to read from a stream of character data. The StreamReader class derives from the abstract TextReader class (Figure 1), which declares basic methods for reading characters from a byte stream in a given encoding system. In turn, the StreamReader class implements the methods of the TextReader class and is the main class that is used to read information from text files.
Figure 1. The TextReader and StreamReader classes
The StreamWriter class is used to write to a stream of characters in a given encoding. The class derives from the abstract TextWriter class (Figure 2) and implements its methods. The StreamWriter class is the main class used to write character data to a file.
Figure 2. Classes TextWriter and StreamWriter
In order to use the StreamReader and StreamWriter classes, the program needs to include the System.IO namespace
// Include System.IO namespace using System.IO;
⇑
2. Overview of methods and properties of the StreamReader class
The following is a list of the main methods that are inherited from the TextReader class and implemented in the StreamReader class:
- Close() – closes the StreamReader object and the underlying stream and releases all system resources associated with this object;
- Dispose() – closes the underlying stream and makes it possible to set the release of managed resources;
- Peek() – returns the next available character without shifting the position of the read pointer from the file;
- Read() – reads one or several characters (depending on the implementation) with an offset of the read pointer from the file;
- ReadAsync() – asynchronously reads the specified number of characters from the stream and writes the data to the buffer;
- ReadBlock() – reads an array of characters into the specified buffer;
- ReadBlockAsync() – reads an array of characters from the current stream asynchronously;
- ReadLine() – reads a character string from the stream up to a newline character;
- ReadLineAsync() – reads a character string asynchronously;
- ReadToEnd() – reads all characters from the stream, starting from the current position to the end of the stream;
The StreamReader class has 3 properties that are not inherited from the TextReader class:
- BaseStream – returns the underlying stream;
- CurrentEncoding – returns the current stream encoding;
- EndOfStream – determines if the end of the stream has been reached.
⇑
3. Constructors of StreamReader class. Create a stream associated with a text file
The StreamReader class has a number of overloaded constructors that allow you to access the input stream with various additional options. In general, one of the possible options for creating and using an input stream looks like this
try { // Create an input stream by calling a constructor StreamReader fIn = StreamReader(...); // Use input stream ... // Close input stream fIn.Close(); } catch (ExceptionType1 e) { // Process the ExceptionType1 exception ... } catch (ExceptionType1 e) { // Process the ExceptionType2 exception ... } ... catch (ExceptionTypeN e) { // Process the ExceptionTypeN exception ... }
In the above snippet, ExceptionType1, ExceptionType2 …, ExceptionTypeN are the types of exceptions that can be thrown when using one of the constructors of the StreamReader class.
⇑
3.1. Constructor StreamReader(string)
This constructor initializes a new instance of the StreamReader class for a specific filename. General constructor form
public StreamReader(string path);
here
- path – the path to the file.
When using the constructor, exceptions of the following types can be thrown:
- System.ArgumentException – path is an empty string “”;
- System.ArgumentNullException – path is null;
- System.IO.FileNotFoundException – file not found;
- System.IO.DirectoryNotFoundException – path specified incorrectly;
- System.IO.DirectoryNotFoundException – path specified incorrectly;
Example.
using System; // Include the System.IO namespace using System.IO; namespace ConsoleApp12 { class Program { static void Main(string[] args) { // Create a stream instance using the StreamReader(string) constructor try { StreamReader fInput = new StreamReader("myfile1.txt"); // Use stream // ... // Close stream fInput.Close(); } catch (ArgumentException e) { Console.WriteLine(e.Message); } catch (FileNotFoundException e) { Console.WriteLine(e.Message); } catch (DirectoryNotFoundException e) { Console.WriteLine(e.Message); } catch (IOException e) { Console.WriteLine(e.Message); } } } }
The catch() block chain can be combined into a single block that handles the Exception type as follows
... // Create a stream instance using the StreamReader(string) constructor try { StreamReader fInput = new StreamReader("myfile1.txt"); // Use stream // ... // Close stream fInput.Close(); } catch (System.Exception e) { Console.WriteLine(e.Message); } ...
⇑
3.2. Constructor StreamReader(string, System.Text.Encoding)
When reading the input stream, it is possible to specify the character encoding. To do this, use the constructor
public StreamReader(string path, System.Text.Encoding encoding);
Exceptions of the following types are possible:
- System.ArgumentException – path is an empty string “”;
- System.ArgumentNullException – path is null;
- System.IO.FileNotFoundException – file not found;
- System.IO.DirectoryNotFoundException – the path is incorrect;
- System.NotSupportedException – path includes invalid or false syntax for file name, directory name, or volume label.
Example.
using System; // Include System.IO namespace using System.IO; ... // Create a stream instance try { // Create ASCII character encoding System.Text.Encoding encoding = System.Text.Encoding.ASCII; // Open an input stream in the specified encoding StreamReader fInput = new StreamReader("myfile1.txt", encoding); // Use stream // ... // Close stream fInput.Close(); } catch (System.Exception e) { Console.WriteLine(e.Message); } ...
⇑
3.3. Constructor StreamReader(System.IO.Stream)
Using this constructor, it is possible to create an input stream from another stream inherited from the base Stream class (for example, from a FileStream stream). The general form of such a constructor is as follows
public StreamReader(System.IO.Stream stream);
here stream is a specific stream associated with a file.
When using the constructor, the following exceptions are possible:
- System.ArgumentException – the stream does not support reading;
- System.ArgumentNullException – stream or encoding is null.
Example.
using System; using System.IO; ... // Use the using() statement // 1. Create an instance of a FileStream using (FileStream inputStream = new FileStream("myfile1.txt", FileMode.Open)) { // 2. Create an instance of a StreamReader stream // using the StreamReader (Stream) constructor using (StreamReader fInput = new StreamReader(inputStream)) { // Use stream fInput // ... } } ...
⇑
3.4. Constructor StreamReader(System.IO.Stream, System.Text.Encoding)
This constructor creates an input stream from another input stream based on the specified character encoding. According to the documentation, the constructor declaration is as follows
public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding)
here
- stream – the stream to be read;
- encoding – encoding system (Unicode, UTF-8, UTF 7, etc.).
When using the constructor, the following types of exceptions may be thrown:
- System.ArgumentException – path is an empty string “”;
- System.ArgumentNullException – path is null.
Example.
using System; // Include the System.IO namespace using System.IO; ... try { // 1. Create the instance of FileStream FileStream inputStream = new FileStream("myfile1.txt", FileMode.Open); // 2. Create a StreamReader stream instance // using the StreamReader (Stream, System.Text.Encoding) constructor // in the UTF-8 encoding StreamReader fInput = new StreamReader(inputStream, System.Text.Encoding.UTF8); // Use stream // ... // Close stream fInput.Close(); } catch (System.Exception e) { Console.WriteLine(e.Message); } ...
⇑
4. Using the using() statement when creating an input stream
An input stream of type StreamReader is created using one of the available constructors. Each constructor has its own characteristics and contains a different number of parameters. After working with the input stream, this stream must be closed using the Close() method.
// Include System.IO namespace using System.IO; ... StreamReader fIn = StreamReader(...); // Processing fIn stream ... // Close fIn stream fIn.Close(); ...
There is another way to create an input stream and release the resources associated with it. For this, the using() statement is used, which ensures that resources are automatically cleaned up.
using (StreamReader fIn=StreamReader(...)) { // Process fIn stream ... }
Example. The example uses the using() statement to create a FileStream from the file myfile1.txt. The constructor of the FileStream class is called. An input stream of type StreamReader is then created using a nested using() statement. After use, the streams do not need to be closed using the Close() method, since the resources associated with these streams will be released (closed) automatically.
... // Create the instance of FileStream using (FileStream fs = new FileStream("myfile1.txt", FileMode.Open)) { // Create the StreamReader stream using (StreamReader fIn = new StreamReader(fs)) { // Use the StreamReader // ... } } ...
⇑
Related topics
- Methods of StreamReader class
- StreamWriter class. Purpose. Constructors. Create an output stream in different ways
- Class StreamWriter. Overview of methods and properties
⇑