C# FileStream and StreamReader Tutorial
C# FileStream and StreamReader Tutorial
The FileStream class is a more low-level tool for file handling in C#, allowing byte-level operations to read from or write directly to files. It provides fine control over file access and sharing permissions but requires manual handling of data encoding. In contrast, the StreamWriter class is a higher-level abstraction specifically designed for writing text data, automatically handling character encoding and making it easier to write plain text to files. It is the preferred method for writing string data, due to its simplicity and usability .
In FileStream, encoding is not directly handled, as it operates at the byte level, requiring manual conversion of string data to bytes when writing and vice versa when reading. In contrast, the StreamReader class automatically handles encoding using UTF-8 as its default. This difference makes StreamReader more suitable for text data operations, while FileStream offers lower-level control suitable for byte-wise operations and custom encoding handling .
StreamWriter offers several advantages over FileStream for writing text data to files. StreamWriter simplifies text writing by automatically managing text encoding and providing methods like Write and WriteLine tailored for string data. It abstracts the complexities of converting strings to byte arrays, unlike FileStream, which requires explicit handling of data encoding. Thus, it is more convenient for tasks specifically involving text .
The FileStream class in C# is primarily used for reading from, writing to, and closing files, thus performing basic file operations within the operating system. To create a FileStream object, you need to include the System.IO namespace and instantiate a FileStream with a specified file path, FileMode, FileAccess, and FileShare enumerator. Each of these enumerators defines the manner in which the file is accessed, modified, or shared .
FileAccess controls how a file can be accessed, dictating permission levels for operations. Setting FileAccess to Read, Write, or ReadWrite determines whether the file can be read from, written to, or both. Effective use of FileAccess is crucial for enforcing security policies, reducing unauthorized file operations and minimizing unintended effects, assuring data integrity and security in applications .
The StreamReader class is used for reading text files in a specific encoding in C#, implementing a TextReader that reads characters from a byte stream. It is widely used due to its ease of implementation and default UTF-8 encoding. However, one of its limitations is that it is not thread-safe by default, which can lead to issues in multithreaded environments unless explicitly handled .
FileStream is preferred when lower-level file operations are necessary, such as when working with non-text binary files, requiring specific file access modes and sharing permissions, or when precise control over byte-level data access is needed. It is also useful when custom encoding must be applied manually or when handling file operations that are not character-based or require multi-threading capabilities beyond those provided by StreamReader or StreamWriter .
To read specific lines of text using the StreamReader class, you can iteratively call the ReadLine method inside a loop to read through the file line by line. By using conditional statements, such as if-clauses, you can skip or process specific lines based on your conditions, allowing for targeted reading. This approach offers flexibility to ignore non-relevant lines and only process those of interest .
Using the 'None' option in FileShare while opening files with FileStream means no other process or thread can access the file until the FileStream is released. This can lead to issues in a multi-user or multi-process environment where concurrent access to files is needed, potentially causing program hang or deadlock if another operation attempts to access that file during the lock period .
The FileMode enumerator defines how the operating system should open a file when creating a FileStream object. For instance, FileMode.Create specifies that a new file is created and, if it already exists, the existing file is overwritten. Whereas, FileMode.Append opens a file if it exists and sets the cursor at the end of the file for appending new data. If the file does not exist, it creates a new one. These options control file operations ensuring that actions such as overwriting or appending occur based on the developer's intent .