Group
File Handling in C#
Objective
1. The program reads the content of the binary file.
2. The file is opened for reading, and its length is determined.
3. The program then writes a new file with the bytes in reverse order.
4. The new file is saved with the same name as the original, but with a ".inv" extension.
5. Proper error handling should be included in case the file cannot be read or written to.
Create a program to "invert" a file: create a file with the same name ending in ".inv" and containing the same bytes as the original file but in reverse order (the first byte will be the last, the second will be the penultimate, and so on, until the last byte of the original file, which should appear in the first position of the resulting file).
Example C# Exercise
Show C# Code
using System;
using System.IO;
class InvertFileContent
{
// Main method to execute the program
static void Main(string[] args)
{
// Ask the user for the input file name
Console.WriteLine("Please enter the name of the file to invert:");
// Read the name of the input file from the user
string inputFileName = Console.ReadLine();
// Generate the name of the output file by appending ".inv"
string outputFileName = Path.GetFileNameWithoutExtension(inputFileName) + ".inv" + Path.GetExtension(inputFileName);
try
{
// Open the input file for reading in binary mode
using (BinaryReader reader = new BinaryReader(File.Open(inputFileName, FileMode.Open)))
{
// Open the output file for writing in binary mode
using (BinaryWriter writer = new BinaryWriter(File.Open(outputFileName, FileMode.Create)))
{
// Get the length of the input file in bytes
long fileLength = reader.BaseStream.Length;
// Loop through the file in reverse order
for (long i = fileLength - 1; i >= 0; i--)
{
// Move to the byte at position i in the file
reader.BaseStream.Seek(i, SeekOrigin.Begin);
// Read the byte at the current position
byte currentByte = reader.ReadByte();
// Write the byte to the output file
writer.Write(currentByte);
}
// Notify the user that the operation was successful
Console.WriteLine($"The content has been successfully inverted and saved to {outputFileName}");
}
}
}
catch (FileNotFoundException)
{
// If the file is not found, inform the user
Console.WriteLine("Error: The specified file could not be found.");
}
catch (Exception ex)
{
// Handle any other unexpected errors
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
Output
//If the input file data.bin contains the following bytes (in hexadecimal format):
01 02 03 04 05
//The output file data.inv will contain the reversed bytes:
05 04 03 02 01