Ejercicio
Lectura De Un Archivo Binario (1: BMP)
Objectivo
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).
Ejemplo Ejercicio C#
Mostrar Código C#
// 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.");
}
}
}
Salida
Enter the BMP file path:
If the file is valid: The file appears to be a valid BMP image.
If the file is not valid: The file does not appear to be a valid BMP image.
Código de Ejemplo Copiado!
Comparte este Ejercicio C# Sharp
¡Explora nuestro conjunto de ejercicios de programación C# Sharp! Estos ejercicios, diseñados específicamente para principiantes, te ayudarán a desarrollar una sólida comprensión de los conceptos básicos de C#. Desde variables y tipos de datos hasta estructuras de control y funciones simples, cada ejercicio está diseñado para desafiarte de manera gradual a medida que adquieres confianza en la codificación en C#.
En este ejercicio de C#, se debe crear un programa que pida al usuario su nombre, edad (como byte) y el año en que nació (como int), y almacene estos da...
En este ejercicio de C#, se debe crear un traductor básico de C# a Java. El programa debe aceptar archivos fuente de C# y crear un archivo fuente...
Este ejercicio en C# tiene como objetivo enseñar cómo manipular archivos de texto y cómo invertir su contenido utilizando estructuras de programación básicas. En este...
Este ejercicio en C# tiene como objetivo enseñar cómo verificar la validez de un archivo de imagen GIF. En este ejercicio, se requiere crear un programa que le...
Este ejercicio en C# tiene como objetivo ampliar una base de datos de amigos, permitiendo que los datos se carguen desde un archivo al inicio de ...
Este ejercicio en C# consiste en crear un traductor básico de Pascal a C#. El programa debe aceptar código escrito en Pascal y convertirlo en un ...