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
C# Exercise Example
// 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);
}
}