C# Tutorial
C# String
C# Array
C# Flow Control
C# Class and Object
C# Inheritance
C# Interface
C# Collection
C# Generic
C# File I/O
C# Delegate and Event
C# Exception
C# Process and Thread
C# ADO.NET Database Operations
In this tutorial, we'll demonstrate how to use the FileStream class in C# for reading and writing data to and from a file. Let's get started!
Create a new C# Console Application using Visual Studio or any other C# development environment. Name it FileStreamTutorial
.
Add the following using statement at the beginning of the Program.cs
file:
using System.IO;
Now, let's write some data to a file using the FileStream class. Add the following method to the Program
class:
public static void WriteDataToFile() { string filePath = "example.txt"; byte[] dataToWrite = System.Text.Encoding.UTF8.GetBytes("Hello, FileStream!"); using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { fileStream.Write(dataToWrite, 0, dataToWrite.Length); } Console.WriteLine("Data written to file successfully!"); }
This method creates a new file named example.txt
, writes the string "Hello, FileStream!" as bytes, and then closes the file.
Next, let's read the data from the file we've just created. Add the following method to the Program
class:
public static void ReadDataFromFile() { string filePath = "example.txt"; using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { byte[] dataRead = new byte[fileStream.Length]; fileStream.Read(dataRead, 0, dataRead.Length); string content = System.Text.Encoding.UTF8.GetString(dataRead); Console.WriteLine("Data read from file: " + content); } }
This method opens the example.txt
file, reads its content as bytes, and then converts the bytes back to a string.
Now, let's call these methods in the Main
method of the Program
class:
static void Main() { WriteDataToFile(); ReadDataFromFile(); Console.ReadKey(); }
Now, run the application. You should see the following output:
Data written to file successfully! Data read from file: Hello, FileStream!
This concludes the basic tutorial on using the FileStream class in C# for reading and writing data to and from a file. There are other features available, such as seeking to specific positions in a file, but this tutorial should give you a solid starting point.
Working with FileStream in C#:
FileStream
is part of the System.IO
namespace and enables you to read from and write to files byte by byte or block by block.using System; using System.IO; class Program { static void Main() { string filePath = "example.txt"; // Create a FileStream for reading using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { // Read from the file byte[] buffer = new byte[1024]; int bytesRead = fileStream.Read(buffer, 0, buffer.Length); // Process the read data (e.g., convert bytes to string) string content = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead); Console.WriteLine($"Read content: {content}"); } } }
C# FileStream write example:
FileStream
for writing data to a file.using System; using System.IO; class Program { static void Main() { string filePath = "example.txt"; // Create a FileStream for writing using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { // Write data to the file string content = "Hello, FileStream!"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(content); fileStream.Write(buffer, 0, buffer.Length); } Console.WriteLine($"Data written to '{filePath}'."); } }
Reading binary files with FileStream in C#:
FileStream
can read binary files by reading bytes directly.using System; using System.IO; class Program { static void Main() { string filePath = "binaryFile.dat"; // Create a FileStream for reading binary data using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { // Read binary data from the file byte[] buffer = new byte[1024]; int bytesRead = fileStream.Read(buffer, 0, buffer.Length); // Process the binary data as needed // ... } } }
Writing binary files with FileStream in C#:
FileStream
can write binary data to a file by writing bytes directly.using System; using System.IO; class Program { static void Main() { string filePath = "binaryFile.dat"; // Create a FileStream for writing binary data using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { // Write binary data to the file byte[] binaryData = { 0x41, 0x42, 0x43, 0x44 }; // Example binary data fileStream.Write(binaryData, 0, binaryData.Length); } Console.WriteLine($"Binary data written to '{filePath}'."); } }
C# FileStream seek method:
Seek
method of FileStream
is used to set the position within the file.using System; using System.IO; class Program { static void Main() { string filePath = "example.txt"; // Create a FileStream for reading using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { // Seek to a specific position in the file fileStream.Seek(10, SeekOrigin.Begin); // Read data from the new position byte[] buffer = new byte[1024]; int bytesRead = fileStream.Read(buffer, 0, buffer.Length); // Process the read data string content = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead); Console.WriteLine($"Read content after seeking: {content}"); } } }
C# FileStream asynchronous read and write:
FileStream
(ReadAsync
and WriteAsync
) allow non-blocking file operations.using System; using System.IO; using System.Threading.Tasks; class Program { static async Task Main() { string filePath = "example.txt"; // Create a FileStream for reading asynchronously using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[1024]; // Asynchronously read data from the file int bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length); // Process the read data string content = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead); Console.WriteLine($"Read content asynchronously: {content}"); } } }
Appending to a file with FileStream in C#:
FileStream
for appending content to an existing file.using System; using System.IO; class Program { static void Main() { string filePath = "example.txt"; // Create a FileStream for appending using (FileStream fileStream = new FileStream(filePath, FileMode.Append, FileAccess.Write)) { // Append data to the file string appendedContent = "\nAppended content with FileStream."; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(appendedContent); fileStream.Write(buffer, 0, buffer.Length); } Console.WriteLine($"Data appended to '{filePath}'."); } }
File locking with FileStream in C#:
FileStream
can be used for file locking to prevent concurrent access by multiple processes.using System; using System.IO; class Program { static void Main() { string filePath = "example.txt"; // Create a FileStream for exclusive file access using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None)) { // Perform operations on the locked file // ... Console.WriteLine($"File is locked for exclusive access."); } } }