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

C# FileStream Class: File Read And Write

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 Console Application:

Create a new C# Console Application using Visual Studio or any other C# development environment. Name it FileStreamTutorial.

  • Import required namespace:

Add the following using statement at the beginning of the Program.cs file:

using System.IO;
  • Writing data to a file using FileStream:

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.

  • Reading data from a file using FileStream:

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.

  • Call the methods in the Main method:

Now, let's call these methods in the Main method of the Program class:

static void Main()
{
    WriteDataToFile();
    ReadDataFromFile();
    Console.ReadKey();
}
  • Run the application:

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.

  1. Working with FileStream in C#:

    • Description: 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.
    • Code:
      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}");
              }
          }
      }
      
  2. C# FileStream write example:

    • Description: Use FileStream for writing data to a file.
    • Code:
      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}'.");
          }
      }
      
  3. Reading binary files with FileStream in C#:

    • Description: FileStream can read binary files by reading bytes directly.
    • Code:
      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
                  // ...
              }
          }
      }
      
  4. Writing binary files with FileStream in C#:

    • Description: FileStream can write binary data to a file by writing bytes directly.
    • Code:
      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}'.");
          }
      }
      
  5. C# FileStream seek method:

    • Description: The Seek method of FileStream is used to set the position within the file.
    • Code:
      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}");
              }
          }
      }
      
  6. C# FileStream asynchronous read and write:

    • Description: Asynchronous methods of FileStream (ReadAsync and WriteAsync) allow non-blocking file operations.
    • Code:
      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}");
              }
          }
      }
      
  7. Appending to a file with FileStream in C#:

    • Description: Use FileStream for appending content to an existing file.
    • Code:
      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}'.");
          }
      }
      
  8. File locking with FileStream in C#:

    • Description: FileStream can be used for file locking to prevent concurrent access by multiple processes.
    • Code:
      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.");
              }
          }
      }