Home » C# programs » C# FileStream class programs

C# program to read and write a byte array to file using FileStream class

In this article we will learn, how to read and write a byte array into file? Here we use FileStream class and its methods Read and Write for read and write respectively.
Submitted by IncludeHelp, on November 17, 2017

Syntax:

void  Read (byte[] b, int offset, int count);
void  Write(byte[] b, int offset, int count);

Parameters:

  • b : byte array
  • offset : location of file
  • count : Total bytes read/write to or from file.

Example:

using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            byte[] b1 = { 10, 20, 24, 13, 15, 17 };
            byte[] b2 = new byte[6];

            byte large = 0;
            FileStream f1;
            f1 = new FileStream("abc.txt", FileMode.Create, FileAccess.Write);

            f1.Write(b1,0,6);
            f1.Close();

            f1 = new FileStream("abc.txt", FileMode.Open, FileAccess.Read);

            f1.Read(b2, 0, 6);

            large = b2[0];
            for (int i = 1; i < b2.Length; i++)
            { 
                if (large < b2[i])
                    large = b2[i];
            }

            Console.WriteLine("Largest Item is : " + large);
            f1.Close();
        }
    }
}

Output

Largest Item is : 24

In this program, we are performing read and write operation into file and find largest element from file.

In above program, we need to remember, when we use "FileStream" class then we need to include System.IO namespace in the program.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.