Group
File Handling in C#
Objective
1. The program reads the file header of a PCX image.
2. It checks if the file is a valid PCX image by verifying the ID and version.
3.The program extracts the Xmin, Ymin, Xmax, and Ymax values from the header to compute the image width and height.
4. The width is calculated as Xmax - Xmin + 1, and the height as Ymax - Ymin + 1.
5. If the file is a valid PCX image, it will display the width and height of the image. Otherwise, it will output an error message.
Example usage:
checkPcxImage image.pcx
Create a program that checks if a file is a PCX image and, if so, displays its width and height using the given PCX format specifications.
Example C# Exercise
Show C# Code
using System;
using System.IO;
class PcxImageChecker
{
// Main method where the program starts execution
static void Main(string[] args)
{
// Check if the user provided a filename as a command line argument
if (args.Length != 1)
{
Console.WriteLine("Usage: checkPcxImage ");
return;
}
// Get the file path from the command line argument
string fileName = args[0];
// Try to read the file
try
{
// Open the file for reading
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
// Read the first byte to check the file ID (should be 10 for PCX)
byte id = (byte)fs.ReadByte();
if (id != 10) // 10 indicates that it's a valid PCX file
{
Console.WriteLine("Not a valid PCX file.");
return;
}
// Skip version, encoding, and bits per pixel (we are only interested in the coordinates)
fs.Seek(4, SeekOrigin.Begin);
// Read Xmin, Ymin, Xmax, Ymax (4 bytes in total)
byte[] coordinates = new byte[4];
fs.Read(coordinates, 0, 4);
// Extract Xmin, Ymin, Xmax, Ymax values from the byte array
int Xmin = coordinates[0];
int Ymin = coordinates[1];
int Xmax = coordinates[2];
int Ymax = coordinates[3];
// Calculate the width and height of the image
int width = Xmax - Xmin + 1;
int height = Ymax - Ymin + 1;
// Display the width and height of the image
Console.WriteLine($"This is a valid PCX image.");
Console.WriteLine($"Width: {width} pixels");
Console.WriteLine($"Height: {height} pixels");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error reading the file: {ex.Message}");
}
}
}
Output
//Case 1 - Valid PCX Image:
//For the command:
checkPcxImage image.pcx
//Output:
This is a valid PCX image.
Width: 100 pixels
Height: 200 pixels
//Case 2 - Invalid File (Not a PCX Image):
//For the command:
checkPcxImage invalidFile.txt
//Output:
Not a valid PCX file.