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
{
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("Usage: checkPcxImage ");
return;
}
string fileName = args[0];
try
{
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
byte id = (byte)fs.ReadByte();
if (id != 10)
{
Console.WriteLine("Not a valid PCX file.");
return;
}
fs.Seek(4, SeekOrigin.Begin);
byte[] coordinates = new byte[4];
fs.Read(coordinates, 0, 4);
int Xmin = coordinates[0];
int Ymin = coordinates[1];
int Xmax = coordinates[2];
int Ymax = coordinates[3];
int width = Xmax - Xmin + 1;
int height = Ymax - Ymin + 1;
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.