Exercise
Reading a binary file (1: BMP)
Objetive
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).
Example Code
// 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.");
}
}
}