Writing To A Binary File - C# Programming Exercise

In this exercise of C#, you need to create a program that asks the user for their name, age (as a byte), and the year they were born (as an int), and stores this data in a binary file. Then, you should create a reader to check that the data has been stored correctly. This exercise is a great way to learn how to work with binary files in C#, which is an essential skill when dealing with large data volumes or when you need to store information efficiently. It also teaches how to serialize and deserialize data in binary format, which is useful when you want to save information compactly and retrieve it quickly.

Through this exercise, programmers will learn how to interact with the file system, store data in a structured way, and ensure correct reading and writing of this data, which improves the input and output management in their applications.

 Category

File Management

 Exercise

Writing To A Binary File

 Objective

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.

 Write Your C# Exercise

// Importing necessary namespaces for file handling and data types
using System;
using System.IO;

public class BinaryDataWriter
{
    // Method to write user data into a binary file
    public static void WriteDataToFile(string filePath)
    {
        // Asking the user for their name, age, and birth year
        Console.Write("Enter your name: ");
        string name = Console.ReadLine();

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

        Console.Write("Enter your birth year (int): ");
        int birthYear = int.Parse(Console.ReadLine());

        // Creating a binary writer to write data to the file
        using (BinaryWriter writer = new BinaryWriter(File.Open(filePath, FileMode.Create)))
        {
            // Writing the user's name, age, and birth year to the binary file
            writer.Write(name);
            writer.Write(age);
            writer.Write(birthYear);
        }
    }
}

public class BinaryDataReader
{
    // Method to read user data from a binary file and display it
    public static void ReadDataFromFile(string filePath)
    {
        // Checking if the file exists
        if (File.Exists(filePath))
        {
            // Creating a binary reader to read data from the file
            using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
            {
                // Reading the data from the binary file
                string name = reader.ReadString();
                byte age = reader.ReadByte();
                int birthYear = reader.ReadInt32();

                // Displaying the read data
                Console.WriteLine("\nData read from the file:");
                Console.WriteLine($"Name: {name}");
                Console.WriteLine($"Age: {age}");
                Console.WriteLine($"Birth Year: {birthYear}");
            }
        }
        else
        {
            Console.WriteLine("The specified file does not exist.");
        }
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        // Path for the binary file to store user data
        string filePath = "user_data.bin";

        // Writing data to the binary file
        BinaryDataWriter.WriteDataToFile(filePath);

        // Reading and displaying the data from the binary file to verify
        BinaryDataReader.ReadDataFromFile(filePath);
    }
}

 Share this C# exercise

 More C# Programming Exercises of File Management

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  C# to Java

    In this exercise of C#, you need to create a basic C# to Java translator. The program should accept C# source files and generate an equivalent ...

  •  Invert a text file

    This C# exercise aims to teach how to manipulate text files and reverse their content using basic programming structures. In this exercise, you need to create ...

  •  Reading a binay file (2 - GIF)

    This C# exercise aims to teach how to check the validity of a GIF image file. In this exercise, you need to create a program that reads the first four bytes of...

  •  Friends database, using files

    This C# exercise aims to expand a friends database by allowing data to be loaded from a file at the beginning of each session and saved to...

  •  Pascal to C# translator

    This C# exercise involves creating a basic Pascal to C# translator. The program should accept code written in Pascal and convert it to an equival...

  •  Convert a text file to uppercase

    This C# exercise involves creating a program that reads a text file and dumps its content into another file, making a transformation in the process. The transformatio...