FileStream in C# is used to read from, write to, and manipulate files at the byte level.
It’s part of the System.IO namespace and provides fine-grained control over file operations, making it ideal for handling binary data and working with large files.
In this tutorial, we’ll cover:
1. Basics of FileStream
FileStream allows you to work directly with files as streams of bytes. To create a FileStream object, you can specify the file path, access mode, and file access level. Common modes include:
- FileMode: Specifies how the file should be opened, such as FileMode.Create, FileMode.Open, FileMode.Append, etc.
- FileAccess: Specifies the access level for the file, like FileAccess.Read, FileAccess.Write, or FileAccess.ReadWrite.
Example: Basic FileStream Setup
using System; using System.IO; public class FileStreamBasic { public static void Main() { // Creating a FileStream object to write to a file using (FileStream fs = new FileStream("example.txt", FileMode.Create, FileAccess.Write)) { // FileStream setup completed, ready to write data Console.WriteLine("FileStream created for writing."); } } }
Explanation:
- A FileStream object named fs is created with FileMode.Create and FileAccess.Write, ready to write to the file named example.txt.
- The using statement ensures that the file is closed automatically when done.
2. Writing to a File with FileStream
To write data to a file using FileStream, you convert the data into bytes and write it using Write().
Example: Writing to a File
using System; using System.IO; using System.Text; public class FileStreamWriteExample { public static void Main() { string data = "Hello, FileStream!"; byte[] dataBytes = Encoding.UTF8.GetBytes(data); using (FileStream fs = new FileStream("write_example.txt", FileMode.Create, FileAccess.Write)) { fs.Write(dataBytes, 0, dataBytes.Length); Console.WriteLine("Data written to file."); } } }
Explanation:
- Encoding.UTF8.GetBytes(data) converts the string data to a byte array.
- fs.Write(dataBytes, 0, dataBytes.Length) writes the byte array to write_example.txt, starting at index 0 and writing dataBytes.Length bytes.
Output in write_example.txt:
Hello, FileStream!
3. Reading from a File with FileStream
To read data from a file using FileStream, use the Read() method. This method reads bytes from the file and stores them in a byte array.
Example: Reading from a File
using System; using System.IO; using System.Text; public class FileStreamReadExample { public static void Main() { using (FileStream fs = new FileStream("write_example.txt", FileMode.Open, FileAccess.Read)) { byte[] dataBytes = new byte[fs.Length]; fs.Read(dataBytes, 0, dataBytes.Length); string data = Encoding.UTF8.GetString(dataBytes); Console.WriteLine("Data read from file: " + data); } } }
Explanation:
- A byte array dataBytes is created with a size equal to the file length (fs.Length).
- fs.Read(dataBytes, 0, dataBytes.Length) reads bytes from the file into dataBytes.
- Encoding.UTF8.GetString(dataBytes) converts the byte array back to a string for display.
Output:
Data read from file: Hello, FileStream!
4. Appending Data to a File
To add more data to an existing file, open the file in FileMode.Append and use the Write() method to add data at the end of the file.
Example: Appending Data to a File
using System; using System.IO; using System.Text; public class FileStreamAppendExample { public static void Main() { string data = " This is appended text."; byte[] dataBytes = Encoding.UTF8.GetBytes(data); using (FileStream fs = new FileStream("write_example.txt", FileMode.Append, FileAccess.Write)) { fs.Write(dataBytes, 0, dataBytes.Length); Console.WriteLine("Data appended to file."); } } }
Explanation:
- The file write_example.txt is opened in FileMode.Append, allowing new data to be added to the end.
- The new text is converted to bytes and written to the file, following the existing content.
Updated Output in write_example.txt:
Hello, FileStream! This is appended text.
5. Practical Example: Copying a File with FileStream
This example demonstrates reading from one file and writing to another, essentially creating a file copy.
Example: Copying a File
using System; using System.IO; public class FileStreamCopyExample { public static void Main() { string sourceFile = "write_example.txt"; string destinationFile = "copy_example.txt"; using (FileStream sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read)) using (FileStream destinationStream = new FileStream(destinationFile, FileMode.Create, FileAccess.Write)) { byte[] buffer = new byte[1024]; // Buffer to hold bytes int bytesRead; while ((bytesRead = sourceStream.Read(buffer, 0, buffer.Length)) > 0) { destinationStream.Write(buffer, 0, bytesRead); } Console.WriteLine("File copied successfully."); } } }
Explanation:
- A buffer is created to hold data chunks (1024 bytes at a time).
- The sourceStream.Read method reads data into the buffer, and destinationStream.Write writes it to the new file.
- This process repeats until the entire file is copied.
Output:
File copied successfully.
Content in copy_example.txt:
Hello, FileStream! This is appended text.
Advanced Example: Using FileStream with Binary Data
FileStream is ideal for working with binary data, such as image or audio files. In this example, we read and write an image file using FileStream.
Example: Reading and Writing Binary Data
using System; using System.IO; public class FileStreamBinaryExample { public static void Main() { string sourceFile = "image.png"; string destinationFile = "image_copy.png"; using (FileStream sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read)) using (FileStream destinationStream = new FileStream(destinationFile, FileMode.Create, FileAccess.Write)) { byte[] buffer = new byte[4096]; // Larger buffer for binary data int bytesRead; while ((bytesRead = sourceStream.Read(buffer, 0, buffer.Length)) > 0) { destinationStream.Write(buffer, 0, bytesRead); } Console.WriteLine("Binary file copied successfully."); } } }
Explanation:
- This code works similarly to the previous copy example, but with a larger buffer to accommodate binary data efficiently.
- This approach is especially useful for large files, where loading the entire file into memory may not be feasible.
Output:
Binary file copied successfully.
Summary
FileStream in C# provides a powerful, low-level API for reading from, writing to, and manipulating files in byte form.
Here’s a recap of the main points:
- Basic Setup: Use FileStream with FileMode and FileAccess to control file operations.
- Writing to a File: Convert data to bytes and use Write() to write data to a file.
- Reading from a File: Use Read() to read bytes and convert them back to readable data.
- Appending Data: Open a file in FileMode.Append to add data to the end of the file.
- Copying Files: Use Read() and Write() with a buffer to copy files efficiently.
- Binary Data: FileStream is suitable for handling binary files like images and audio due to its low-level access.
FileStream is ideal for applications that require fine-grained control over file operations, especially when working with large files or binary data in C#.