C# FileStream
In C#, the FileStream class is used to read and write to files on disk. It provides a flexible and low-level way to interact with files, allowing you to read or write individual bytes or larger chunks of data. In this tutorial, we'll discuss how to use the FileStream class in C# to read and write files.
Syntax
The syntax for creating a new FileStream instance is as follows:
FileStream fs = new FileStream(path, mode);
Where path
is the path to the file to read or write and mode
is the FileMode enumeration value that specifies how to open the file.
Example
Let's say we want to read a text file from disk and print its contents to the console. Here's how we can implement it:
using System;
using System.IO;
class Program {
static void Main(string[] args) {
string path = "test.txt";
using FileStream fs = new FileStream(path, FileMode.Open);
using StreamReader sr = new StreamReader(fs);
string line;
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
}
}
In this example, we first created a new FileStream instance with FileMode.Open which opens the file for reading. We then created a new StreamReader instance that is used to read the contents of the file.
Output
When we run the example code above, the output will be the contents of the "test.txt" file:
This is a test file.
It has multiple lines.
This is the last line.
Explanation
In the example above, we opened a text file for reading by creating a new FileStream instance with FileMode.Open. We then created a StreamReader instance that is used to read the contents of the file one line at a time. We used a while loop to read each line of the file and print it to the console.
Use
The FileStream class in C# is useful for reading and writing files on disk. It provides a low-level way to interact with files and allows you to read or write data in a flexible and granular manner.
Important Points
- Always use a using block with a FileStream instance to automatically dispose of it and free up system resources.
- Make sure to specify the correct FileMode enumeration value when creating a new FileStream instance to avoid overwriting existing files or opening files that don't exist.
- You can use the FileStream class to read and write binary files as well as text files.
Summary
In this tutorial, we discussed how to use the FileStream class in C# to read and write files. We covered the syntax, example, output, explanation, use, and important points of the FileStream class in C#. With this knowledge, you can now use the FileStream class to work with files in your C# applications.