Skip to content
Related Articles
Open in App
Not now

Related Articles

C# Program to Read and Write a Byte Array to File using FileStream Class

Improve Article
Save Article
  • Last Updated : 28 Jan, 2022
Improve Article
Save Article

Given a file, now our task is to read and write byte array to a file with the help of FileStream Class Filestream class in C# is the part of System.IO namespace and System.Runtime.dll assembly. This class offers a stream for a file that supports synchronous and asynchronous read and write operations. This class can be used to read from, write to, open, and close files on a file system. The input and output buffers and that is why it gives better performance. This class provides different types of methods and the read and write method is one of them.

1. Read() method: This method is used to read the bytes from the stream and write the data in the specified buffer. 

Syntax:

void  Read (byte[] arr, int loc, int count);

Here, arr is a byte array, loc is the byte offset in arr at which the read bytes will be put, and the count is the total bytes read/write to or from a file. 

Exception: This method also throws some exceptions:

  • ArgumentNullException: This exception is thrown when the arr is null.
  • ArgumentOutOfRangeException: This exception is thrown when the loc or count is negative.
  • NotSupportedException: This exception is thrown when the stream does not support reading.
  • IOException: This exception is thrown when an I/O error occurs.
  • ArgumentException: This exception is thrown when the value of loc and count is an invalid range in the array.

This method also has an overloaded method that is Read(Span<Byte>). This method is used to read a sequence of the bytes from the given file stream and advance the position by the number of bytes read in the given file stream.

Syntax:

public override int Read (Span<byte> buff);

2. Write() method: This method is used to read a sequence of bytes to the file stream.

void Write(byte[] arr, int loc, int count);

Here, arr is a byte array, loc is the 0-based byte offset in arr at which the copying of bytes starts to the stream, and the count is the total bytes read/write to or from a file. 

Exception: This method also throws some exceptions:

  • ArgumentNullException: This exception is thrown when the arr is null.
  • ArgumentOutOfRangeException: This exception is thrown when the loc or count is negative.
  • NotSupportedException: This exception is thrown when the stream does not support reading.
  • ObjectDisposedException: This exception is thrown when the specified stream is closed.
  • IOException: This exception is thrown when an I/O error occurs.
  • ArgumentException: This exception is thrown when the value of loc and count is an invalid range in the array.

This method also has an overloaded method that is Read(Span<Byte>). This method is used to write a sequence of the bytes from a read-only span to the given file stream and advance the position by the number of bytes written in the given file stream.

Syntax:

public override int Write(Span<byte> buff);

Read and Write Byte array to file using FileStream Class

In this program, we have used read and write operations to file and find the largest element from the file.

C#




// C# program to read and write a byte array to
// file using FileStream Class
using System;
using System.IO;
 
class GFG
{
 
    static public void Main()
    {
 
        // Initializing byte arrays
        byte[] arr1 = { 4, 25, 40, 3, 11, 18, 7 };
        byte[] arr2 = new byte[7];
 
        // initializing values
        byte largest = 0;
 
        // FileStream instance
        FileStream file;
 
        file = new FileStream("GeeksforGeeks.txt",
                              FileMode.Create,
                              FileAccess.Write);
 
        // Using write() method
        // Write the bytes
        file.Write(arr1, 0, 7);
 
        // Closing the file
        file.Close();
 
        // Instantiating
        file = new FileStream("GeeksforGeeks.txt",
                              FileMode.Open,
                              FileAccess.Read);
 
        // Using Read() method
        // Read the bytes
        file.Read(arr2, 0, 7);
 
        largest = arr2[0];
        for (int n = 1; n < arr2.Length; n++)
        {
            if (largest < arr2[n])
                largest = arr2[n];
        }
 
        Console.WriteLine("The largest element is : " +
                          largest);
 
        // Close the file
        file.Close();
    }
}


Output:

The largest element is : 40

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!