Programming Course in C# ¡Free!

Reading a binary file (1: BMP)

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

Create a C# program to check if a BMP image file seems to be correct.

It must see if the first two bytes are B and M (ASCII codes 0x42 and 0x4D).



using System;
using System.IO;

public class BmpFile
public static void Main() 
byte data1, data2;

BinaryReader file;
file = new BinaryReader( File.Open( "1.bmp", FileMode.Open ) );

data1 = file.ReadByte();
data2 = file.ReadByte();


if ((data1 == 0x42) && (data2 == 0x4D))  // B M
Console.WriteLine("It seems to be a BMP file");
Console.WriteLine("It DOES NOT seem to be a BMP file");