Writing to a binary file Learn programming C#

Lesson:

File Management


Exercise:

Writing to a binary file


Objetive:

Create a program which asks the user for his name, his age (byte) and the year in which he was born (int) and stores them in a binary file.

Create also a reader to test that those data have been stored correctly.


Code:

using System;
using System.IO;
class BinaryWriterTest
{
    static void Main(string[] args)
    {
        Console.Write("Enter your name: ");
        string name = Console.ReadLine();

        Console.Write("Enter your age: ");
        byte age = Convert.ToByte(Console.ReadLine());

        Console.Write("Enter your year of birth: ");
        int yearOfBirth = Convert.ToInt32(Console.ReadLine());

        BinaryWriter file = new BinaryWriter(
          File.Open("data.dat", FileMode.Create));

        //Write data
        file.Write(name);
        file.Write(age);
        file.Write(yearOfBirth);

        file.Close();

        string datas;
        byte datab;
        int datai;

        BinaryReader inputFile = new BinaryReader(
          File.Open("data.dat", FileMode.Open));

        datas = inputFile.ReadString();
        datab = inputFile.ReadByte();
        datai = inputFile.ReadInt32();

        inputFile.Close();

        Console.WriteLine(datas);
        Console.WriteLine(datab);
        Console.WriteLine(datai);

        if ((datas != name) || (datab != age) || (datai != yearOfBirth))
            Console.WriteLine("Error in data");
        else
            Console.WriteLine("Read error");
    }
}

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.