Reading A Binary File (1: BMP) - C# Programming Exercise

In this exercise of C#, you need to create a program that checks if a BMP image file seems to be correct. The program must verify if the first two bytes of the file are "B" and "M" (ASCII codes 0x42 and 0x4D, respectively). This exercise is great for learning how to work with binary files and how to read their first bytes to validate them. It also teaches how to handle image files, ensuring that the file is correctly formatted from its header, which is crucial for BMP image integrity.

Through this exercise, programmers will learn how to open and read binary files in C#, detect basic format errors, and handle potential issues when working with image files, ensuring that only valid files are processed or used.

 Category

File Management

 Exercise

Reading A Binary File (1: BMP)

 Objective

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).

 Write Your C# Exercise

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

public class BMPChecker
{
    // Method to check if a BMP file starts with "BM"
    public static bool IsBMPFileValid(string filePath)
    {
        // Using FileStream to read the binary content of the file
        using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            // Checking if the file has at least two bytes to read
            if (fileStream.Length < 2)
            {
                // Returning false if file size is less than 2 bytes
                return false;
            }

            // Reading the first two bytes from the file
            int firstByte = fileStream.ReadByte();
            int secondByte = fileStream.ReadByte();

            // Checking if the first two bytes are 'B' (0x42) and 'M' (0x4D)
            return (firstByte == 0x42 && secondByte == 0x4D);
        }
    }
}

// Auxiliary class with Main method for testing the BMPChecker functionality
public class Program
{
    public static void Main(string[] args)
    {
        // Variable to store the file path
        string filePath;

        // Checking if the file path is provided as an argument
        if (args.Length == 1)
        {
            // Assigning the argument to the filePath variable
            filePath = args[0];
        }
        else
        {
            // Prompting the user for the file path if not provided as an argument
            Console.Write("Enter the BMP file path: ");
            filePath = Console.ReadLine();
        }

        // Checking if the specified file exists
        if (File.Exists(filePath))
        {
            // Calling the IsBMPFileValid method to validate the BMP file
            bool isValidBMP = BMPChecker.IsBMPFileValid(filePath);

            // Displaying the result to the user
            if (isValidBMP)
            {
                Console.WriteLine("The file appears to be a valid BMP image.");
            }
            else
            {
                Console.WriteLine("The file does not appear to be a valid BMP image.");
            }
        }
        else
        {
            // Displaying an error message if the file does not exist
            Console.WriteLine("The specified file does not exist.");
        }
    }
}

 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#.

  •  Writing to a binary file

    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 st...

  •  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...