Programming Course in C# ¡Free!

Writing to a binary file

 Saturday, April 06, 2013 published by Exercises C#
Proposed exercise

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.

Output



Solution


using System;
using System.IO;

class WritingBinary
{
static void Main()
{
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 year = Convert.ToInt32(Console.ReadLine());

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

file.Write( name );
file.Write( age );
file.Write( year );

file.Close();

BinaryReader readerFile = new BinaryReader( File.Open("file.dat", FileMode.Open));

string text = readerFile.ReadString();
byte b = readerFile.ReadByte();
int number = readerFile.ReadInt32();

readerFile.Close();

Console.WriteLine(text);
Console.WriteLine(b);
Console.WriteLine(number);

if ((text != name) || (b != age) || (number != year))
Console.WriteLine("Error");
}
}