C# Program to Read and Write a Byte Array to File using FileStream Class - GeeksforGeeks (2024)

    • .NET Framework
    • C# Data Types
    • C# Keywords
    • C# Decision Making
    • C# Methods
    • C# Delegates
    • C# Constructors
    • C# Arrays
    • C# ArrayList
    • C# String
    • C# Tuple
    • C# Indexers
    • C# Interface
    • C# Multithreading
    • C# Exception

    Open In App

    • C# Program to Read and Write a Byte Array to File using FileStream Class
    • How to Read and Write Arrays to/from Files in C++?
    • C# Program to Get File Time Using File Class
    • C++ Program to Read Content From One File and Write it Into Another File
    • Java Program to Write Bytes using ByteStream
    • Java Program to Convert File to a Byte Array
    • Program to convert Byte Array to Writer in Java
    • Java Program to Read Content From One File and Write it into Another File
    • Java Program to Convert String to Byte Array Using getBytes() Method
    • How to Read Data from a CSV File to a 2D Array in C++?
    • How to Read and Write Files Using the New I/O (NIO.2) API in Java?
    • Java Program to Determine Number of Bytes Written to File using DataOutputStream
    • How to Initialize Array With Values Read from a Text File in C++?
    • How to Read a File Using ifstream in C++?
    • Convert byte[] array to File using Java
    • How to Write an ArrayList of Strings into a Text File?
    • Program to convert Byte array to IP Address
    • How to Read and Write a Text File in C#?
    • Read/Write Class Objects from/to File in C++
    • Program to Convert Stream to an Array in Java

    Last Updated : 28 Jan, 2022

    Improve

    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


    bhuwanesh

    Improve

    Next Article

    How to Read and Write Arrays to/from Files in C++?

    Please Login to comment...

    Similar Reads

    Basics of FileStream in C# The FileStream is a class used for reading and writing files in C#. It is part of the System.IO namespace. To manipulate files using FileStream, you need to create an object of FileStream class. This object has four parameters; the Name of the File, FileMode, FileAccess, and FileShare. The Syntax to declare a FileStream object is given as FileStrea 4 min read C# | Byte.CompareTo(Byte) Method This method is used to compare this instance to a specified 8-bit unsigned integer and returns an indication of their relative values.Syntax: public int CompareTo (byte value); Here, the value is an 8-bit unsigned integer to compare.Return Value: This method returns a signed integer that indicates the relative order of this instance and value. Less 2 min read C# | Byte.Equals(Byte) Method This method is used to return a value indicating whether this instance and a specified Byte object represent the same value. Syntax: public bool Equals (byte obj); Here, obj is a byte object to compare to this instance. Return Value: This method returns true if obj is equal to this instance otherwise, it returns false. Below programs illustrate the 2 min read How to Read and Write a Text File in C#? Termination of a program leads to the deletion of all data related to it. Therefore, we need to store the data somewhere. Files are used for permanently storing and sharing data. C# can be used to retrieve and manipulate data stored in text files. Reading a Text file: The file class in C# defines two static methods to read a text file namely File.R 5 min read C# Program To Copy Content Of One File To Another File By Overwriting Same File Name Given a file, now our task is to copy data from one file to another file by overwriting the same file name using C#. So we use the following methods to perform this task: 1. Copy(String, String, Boolean): It is used to copy the content of one file to a new file with overwrite. Syntax: File.Copy(Myfile1, Myfile2, owrite); Where Myfile1 is the first 2 min read C# Program to Get File Time Using File Class Given a file, now our task is to get the file time using the File class. So we use the GetCreationTime() method of the File class. This method is used to find the creation date and time of the given file or directory. This method will only take one parameter that is the path of the file and if this path parameter does not exist, then it will return 2 min read Program to convert Byte array to IP Address Given a Byte Array, convert it to the format of IP Address. Examples: Input : {16, 16, 16, 16} Output : 16.16.16.16Input : {172, 31, 102, 14} Output : 172.31.102.14Byte arrays: A byte is a collection of bits (8). Byte arrays are arrays of contiguous bytes and can be used to store binary information. With byte arrays, one can work directly on bytes 3 min read Converting a String to its Equivalent Byte Array in C# Given a string, the task is to convert this string into a Byte array in C#. Examples: Input: aA Output: [97, 65 ] Input: Hello Output: [ 72, 101, 108, 108, 111 ] Method 1: Using ToByte() Method: This method is a Convert class method. It is used to converts other base data types to a byte data type. Syntax: byte byt = Convert.ToByte(char); Step 1: G 3 min read Difference between byte and sbyte in C# In C#, a single byte is used to store 8-bits value. The byte and sbyte both are used for byte type of data. byte : This Struct is used to represent 8-bit unsigned integers. The byte is an immutable value type and the range of Byte is from 0 to 255. Example : C/C++ Code // C# program to demonstrate // the byte Struct Fields using System; using Syste 2 min read C# | BitConverter.ToString(Byte[]) Method This method is used to convert the numeric value of each element of a specified array of bytes to its equivalent hexadecimal string representation. Syntax: public static string ToString (byte[] value); Here, the value is an array of bytes. Return Value: This method returns a string of hexadecimal pairs separated by hyphens, where each pair represen 2 min read

    Article Tags :

    • C#
    • C# Programs

    We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

    C# Program to Read and Write a Byte Array to File using FileStream Class - GeeksforGeeks (2)

    C# Program to Read and Write a Byte Array to File using FileStream Class - GeeksforGeeks (2024)
    Top Articles
    Latest Posts
    Article information

    Author: Jeremiah Abshire

    Last Updated:

    Views: 5758

    Rating: 4.3 / 5 (74 voted)

    Reviews: 81% of readers found this page helpful

    Author information

    Name: Jeremiah Abshire

    Birthday: 1993-09-14

    Address: Apt. 425 92748 Jannie Centers, Port Nikitaville, VT 82110

    Phone: +8096210939894

    Job: Lead Healthcare Manager

    Hobby: Watching movies, Watching movies, Knapping, LARPing, Coffee roasting, Lacemaking, Gaming

    Introduction: My name is Jeremiah Abshire, I am a outstanding, kind, clever, hilarious, curious, hilarious, outstanding person who loves writing and wants to share my knowledge and understanding with you.