Ejercicio
Lectura de un archivo binario (1: BMP)
Objetivo
Cree un programa de C# para comprobar si un archivo de imagen BMP parece ser correcto.
Debe ver si los dos primeros bytes son B y M (códigos ASCII 0x42 y 0x4D).
Código de Ejemplo
using System;
using System.IO;
public class BMPChecker
{
public static bool IsBMPFileValid(string filePath)
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
if (fileStream.Length < 2)
{
return false;
}
int firstByte = fileStream.ReadByte();
int secondByte = fileStream.ReadByte();
return (firstByte == 0x42 && secondByte == 0x4D);
}
}
}
public class Program
{
public static void Main(string[] args)
{
string filePath;
if (args.Length == 1)
{
filePath = args[0];
}
else
{
Console.Write("Enter the BMP file path: ");
filePath = Console.ReadLine();
}
if (File.Exists(filePath))
{
bool isValidBMP = BMPChecker.IsBMPFileValid(filePath);
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
{
Console.WriteLine("The specified file does not exist.");
}
}
}