C#. Classes BinaryReader and BinaryWriter. Examples of solving tasks

Classes BinaryReader and BinaryWriter. Examples of solving tasks of reading from files and writing data to files in binary format


Contents


Search other websites:




1. Writing to a file and reading from a file numbers of different formats (double, char, string, sbyte). Example

The example demonstrates writing to the file2.bin file and reading the following data from it:

  • numbers of type double;
  • strings of type string;
  • a character of the char type;
  • numbers of type sbyte.

 

using System;
using System.IO;
using System.Text;

namespace ConsoleApp10
{
  class Program
  {
    static void Main(string[] args)
    {
      // Write the following data to the file2.bin file:
      // - number of double type;
      // - a string of type string;
      // - character of type char;
      // - number of sbyte type.

      // 1. Writing numbers
      using (FileStream fs = new FileStream("file2.bin",
FileMode.Create))
      {
        using (BinaryWriter bw = new BinaryWriter(fs, Encoding.Default))
        {
          // 1.2. Original numbers
          double x = 3.88;
          string s = "Hello world!";
          char c = 'Z';
          sbyte b = 17;

          // 1.3. Write numbers - Write() method
          bw.Write(x);
          bw.Write(s);
          bw.Write(c);
          bw.Write(b);
        }
      }

      // 2. Reading numbers
      using (FileStream fs = new FileStream("file2.bin",
FileMode.Open))
      {
        using (BinaryReader br = new BinaryReader(fs, Encoding.Default))
        {
          // 2.1. Variables, in which data is read
          double x2;
          string s2;
          char c2;
          sbyte b2;

          // 2.2. Reading data
          x2 = br.ReadDouble();
          s2 = br.ReadString();
          c2 = br.ReadChar();
          b2 = br.ReadSByte();

          // 2.3. Display the result
          Console.WriteLine("x2 = {0}", x2);
          Console.WriteLine("s2 = {0}", s2);
          Console.WriteLine("c2 = {0}", c2);
          Console.WriteLine("b2 = {0}", b2);
        }
      }
    }
  }
}

The result of the program

x2 = 3.88
s2 = Hello world!
c2 = Z
b2 = 17

 

2. Writing to a file and reading from a file an array of float[] numbers. Example

To write any array, you need to adhere to the following sequence of actions:

  1. Write down the number of elements in the array.
  2. Write the elements of the array in the loop.

When reading an array, you must adhere to the same sequence of actions:

  1. Read the number of elements in the array.
  2. Read the elements of the array using the loop operator.

 

using System;
using System.IO;
using System.Text;

namespace ConsoleApp10
{
  class Program
  {
    static void Main(string[] args)
    {
      // Write the array of float[] numbers to file3.bin
      // 1. Writing numbers
      using (FileStream fs = new FileStream("file3.bin", FileMode.Create))
      {
        using (BinaryWriter bw = new BinaryWriter(fs, Encoding.Default))
        {
          // 1.2. Source array
          float[] AF = { 2.1f, 3.8f, 4.4f, -2.3f, -1.3f };

          // 1.3. Writing the array
          // First write down the number of numbers
          bw.Write(AF.Length);

          // Loop for writing array elements
          for (int i = 0; i < AF.Length; i++)
            bw.Write((double)AF[i]); // written as a double
        }
      }

      // 2. Reading an array of floats from the file
      using (FileStream fs = new FileStream("file3.bin", FileMode.Open))
      {
        using (BinaryReader br = new BinaryReader(fs, Encoding.Default))
        {
          // 2.1. Resulting array
          float[] AF2;

          // 2.2. Read the number of written numbers
          int count = br.ReadInt32();
          AF2 = new float[count];

          // 2.3. Read the array
          for (int i = 0; i < count; i++)
            AF2[i] = (float)br.ReadDouble(); // read as double

          // 2.3. Display the result
          Console.Write("AF2 = { ");
          for (int i = 0; i < AF2.Length; i++)
            Console.Write(AF2[i] + " ");
          Console.WriteLine(" }");
        }
      }
    }
  }
}

Program result

AF2 = { 2.1 3.8 4.4 -2.3 -1.3 }

 

3. A demo program for writing an array of strings (string[]) to a file and reading it from a file. Example

Task. Develop a class named ReadWriteArrayOfStrings that contains two methods:

  • method WriteArrayStr() – writes an array of strings to the file;
  • method ReadArrayStr() – reads strings from a file to array.

Use the BinaryWriter class to write to the file. Use the BinaryReader class to read from the file.
Test the work of the class.

Solution. Since the BinaryWriter and BinaryReader classes are stream adapters, in order to directly access the file, you must use the corresponding class from the basic storage. The FileStream class is used to access files.

using System;
using System.IO;

namespace ConsoleApp10
{
  // A class containing methods for writing/reading an array of strings into a byte stream.
  class ReadWriteArrayOfStrings
  {
    // A method that writes an array of strings to a file.
    // Method parameters:
    // - AS - array of strings;
    // - filename - the name of the file.
    public void WriteArrayStr(string[] AS, string filename)
    {
      // 1. Create a stream and associate it with the file filename
      // The using directive provides automatic cleanup of resources.
      using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
      {
        // 2. Link fs stream to bw instance:
        // bw -> fs -> filename
        BinaryWriter bw = new BinaryWriter(fs);

        // 3. Write the number of strings to the file
        bw.Write(AS.Length);

        // 4. Loop for writing an array of strings to a file
        for (int i = 0; i < AS.Length; i++)
        {
          bw.Write(AS[i]);
        }
      }
    }

    // Method that reads lines from a file
    public string[] ReadArrayStr(string filename)
    {
      // Attempting to open the file for reading
      using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
      {
        // Bind the instance of br to fs:
        // br <- fs <- filename
        BinaryReader br = new BinaryReader(fs);

        // Read the number of elements in the array of strings
        int count = br.ReadInt32();

        // Declare an array of strings and allocate memory for it
        string[] AS = new string[count];

        // Write strings to array AS
        for (int i=0; i<AS.Length; i++)
        {
          // Read the string
          AS[i] = br.ReadString();
        }

        // Return the result
        return AS;
      }
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      // Testing the ReadWriteArrayOfStrings class

      // 1. Create the class instance
      ReadWriteArrayOfStrings obj = new ReadWriteArrayOfStrings();

      // 2. Declare a testable array of strings
      string[] AS = { "abc", "def", "ghi", "jklmn", "jprst" };

      // 3. Call the method for writing lines to the file "myfile.bin"
      obj.WriteArrayStr(AS, "myfile.bin");

      // 4. Read lines into another array from the same file
      string[] AS2 = obj.ReadArrayStr("myfile.bin");

      // 5. Display the lines
      Console.WriteLine("Array AS2:");
      foreach (string s in AS2)
        Console.WriteLine(s);
    }
  }
}

The result of the program

Array AS2:
abc
def
ghi
jklmn
jprst

Once executed, a file named “myfile.bin” will be created.

 

4. An example of writing/reading the array of instances of the Worker class

Task. A Worker class is specified that implements a worker. The class contains the following internal fields:

  • the name of the worker;
  • gender;
  • age;
  • rating.

In the program, you need to sequentially perform the following operations:

  • create an array of instances of the Worker class;
  • write this array to “workers.bin” file in binary format;
  • read data from the “workers.bin” file into another array;
  • display the resulting array on the screen.

Solution. The FileStream class is used to access the file storage. To write to a file in binary format, use the Write() method of the BinaryWriter class. To read the file in binary format, the following BinaryReader class methods are used:

  • ReadInt32() – reads an int from the file stream;
  • ReadDouble() – reads a double;
  • ReadChar() – reads a character of char type;
  • ReadString() – reads a character string.

The text of the program for solving the problem is as follows.

using System;
using System.IO;
using System.Text;

namespace ConsoleApp10
{
  // The class that implements the worker
  class Worker
  {
    // Class fields
    private string name; // Surname, name of the worker
    private char gender; // gender
    private int age; // age in years
    private double rank; // ranking

    // Constructor
    public Worker(string name, char gender, int age, double rank)
    {
      this.name = name;
      this.gender = gender;
      this.age = age;
      this.rank = rank;
    }

    // Class field access properties
    public string Name
    {
      get { return name; }
      set { name = value; }
    }

    public char Gender
    {
      get { return gender; }
      set { gender = value; }
    }

    public int Age
    {
      get { return age; }
      set { age = value; }
    }

    public double Rank
    {
      get { return rank; }
      set { rank = value; }
    }

    // Output method for the current instance
    public void Print(string text)
    {
      Console.Write(text + " ");
      Console.Write("name = {0}, gender = {1}, age = {2}, rank = {3}",
                    name, gender, age, rank);
      Console.WriteLine();
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      // Write an array of Worker instances to the "workers.bin" file
      // 1. Writing an array of instances
      using (FileStream fs = new FileStream("workers.bin",
             FileMode.Create))
      {
        using (BinaryWriter bw = new BinaryWriter(fs, Encoding.Default))
        {
          // 1.1. Create four workers - this is the data to be written
          Worker[] AW = {
            new Worker("Johnson J.", 'M', 42, 4.45),
            new Worker("Johansson S.", 'F', 33, 4.77),
            new Worker("Shcherbyuk I.", 'M', 49, 4.99),
            new Worker("Ivanov I.", 'M', 39, 4.8)
          };

          // 1.2. Writing AW array to file
          // 1.2.1. First write down the number of workers
          bw.Write(AW.Length);

          // 1.2.2. Then, in the loop, write down each worker
          foreach (Worker w in AW)
          {
            // The name of the worker
            bw.Write(w.Name);

            // Gender
            bw.Write(w.Gender);

            // Age
            bw.Write(w.Age);

            // Ranking
            bw.Write(w.Rank);
          }
        }
      }

      // 2. Reading an array of type Worker from "workers.bin" file
      using (FileStream fs = new FileStream("workers.bin", FileMode.Open))
      {
        using (BinaryReader br = new BinaryReader(fs, Encoding.Default))
        {
          // 2.1. Declare an array into which data from the file will be saved,
          // as well as additional variables
          Worker[] AW2;
          string name;
          char gender;
          int age;
          double rank;
          string s; // additional string

          // 2.2. Read the number of saved instances and allocate memory for them
          AW2 = new Worker[br.ReadInt32()];

          // 2.3. Read instances of the Worker class into an AW2 array
          for (int i = 0; i < AW2.Length; i++)
          {
            // read the name
            name = br.ReadString();

            // read gender
            gender = br.ReadChar();

            // read age
            age = br.ReadInt32();

            // read ranking
            rank = br.ReadDouble();

            // Allocate memory for AW2[i] and create the instance
            AW2[i] = new Worker(name, gender, age, rank);
          }

          // 2.4. Display information about read instances of the Worker class
          for (int i = 0; i < AW2.Length; i++)
          {
            // form a string
            s = "AW2[" + Convert.ToString(i) + "]: ";

            // print the instance data
            AW2[i].Print(s);
          }
        }
      }
    }
  }
}

The result of the program

AW2[0]: name = Johnson J., gender = M, age = 42, rank = 4.45
AW2[1]: name = Johansson S., gender = F, age = 33, rank = 4.77
AW2[2]: name = Shcherbyuk I., gender = M, age = 49, rank = 4.99
AW2[3]: name = Ivanov I., gender = M, age = 39, rank = 4.8

 


Related topics