Group
File Handling in C#
Objective
1. The program will prompt the user for the BMP file name.
2. It will open the BMP file in binary mode using BinaryReader.
3. The program will read the specific bytes that correspond to the width and height of the image.
4. It will display the width and height of the image in pixels.
5. If the file is not found or is not a valid BMP file, the program will handle errors appropriately.
Create a C# program to display the width and height of a BMP file using a BinaryReader.
Example C# Exercise
Show C# Code
using System;
using System.IO;
class BMPDimensions
{
// Main method that runs the program
static void Main(string[] args)
{
// Ask the user for the name of the BMP file
Console.WriteLine("Please enter the name of the BMP file:");
// Read the name of the BMP file from the user
string fileName = Console.ReadLine();
try
{
// Open the file in binary mode using BinaryReader
using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
{
// Check if the file starts with "BM" (this indicates it's a BMP file)
reader.BaseStream.Seek(0, SeekOrigin.Begin); // Move to the start of the file
byte[] fileType = reader.ReadBytes(2); // Read the first two bytes
// If the file type is not "BM", it's not a valid BMP file
if (fileType[0] != 0x42 || fileType[1] != 0x4D)
{
Console.WriteLine("This is not a valid BMP file.");
return;
}
// Read the width (bytes 18-21)
reader.BaseStream.Seek(18, SeekOrigin.Begin);
int width = reader.ReadInt32(); // Read the width value
// Read the height (bytes 22-25)
reader.BaseStream.Seek(22, SeekOrigin.Begin);
int height = reader.ReadInt32(); // Read the height value
// Display the width and height of the BMP image
Console.WriteLine($"Width: {width} pixels");
Console.WriteLine($"Height: {height} pixels");
}
}
catch (FileNotFoundException)
{
// Handle file not found error
Console.WriteLine("Error: The specified BMP file could not be found.");
}
catch (Exception ex)
{
// Handle other unexpected errors
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
Output
//If the user enters image.bmp, and the file contains the following data at the relevant positions:
Width: 800 pixels (position 18-21)
Height: 600 pixels (position 22-25)
//The output would be:
Please enter the name of the BMP file:
image.bmp
Width: 800 pixels
Height: 600 pixels