Objective
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).
You must deliver only the ".cs" file, which should contain a comment with your name.
Hint: To know the length of a binary file (BinaryReader), you can use "myFile.BaseStream.Length" and you can jump to a different position with "myFile.BaseStream.Seek(4, SeekOrigin.Current);"
The starting positions we can use are: SeekOrigin.Begin, SeekOrigin.Current- o SeekOrigin.End
Write Your C# Exercise
C# Exercise Example
// Import the System namespace for basic functionality
using System;
// Import the IO namespace for file handling
using System.IO;
class FileInverter
{
static void Main(string[] args)
{
// Ask the user to enter the path of the file to invert
Console.WriteLine("Enter the path of the file to invert:");
// Get the file path entered by the user
string inputFilePath = Console.ReadLine();
// Start of try block to catch any file or IO errors
try
{
// Open the original file in read mode using BinaryReader
using (BinaryReader reader = new BinaryReader(File.Open(inputFilePath, FileMode.Open)))
{
// Get the total length of the file (in bytes)
long fileLength = reader.BaseStream.Length;
// Generate the output file path by appending ".inv" to the original file name
string outputFilePath = inputFilePath + ".inv";
// Open the output file in write mode using BinaryWriter
using (BinaryWriter writer = new BinaryWriter(File.Open(outputFilePath, FileMode.Create)))
{
// Loop through the file in reverse order, from the last byte to the first
for (long i = fileLength - 1; i >= 0; i--)
{
// Move the reader to the byte at the current position
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);
}
}
}
// Inform the user that the inversion process is complete
Console.WriteLine("File has been successfully inverted and saved as: " + inputFilePath + ".inv");
}
catch (Exception ex) // Catch any exceptions that may occur during file operations
{
// Print the exception message if an error occurs
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}