Exercise
Invert Binary File V2
Objective
Create a program to "invert" a file using a "FileStream". The program should 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 of the resulting file should be the last byte of the original file, the second byte should 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.
Please deliver only the ".cs" file, which should contain a comment with your name.
Write Your C# Exercise
C# Exercise Example
// Import the necessary namespaces for file handling
using System;
using System.IO;
class InvertBinaryFile
{
// Main method where the program starts
static void Main(string[] args)
{
// Prompt the user to enter the path of the binary file
Console.WriteLine("Enter the path of the binary file:");
// Get the file path from user input
string filePath = Console.ReadLine();
// Check if the file exists
if (File.Exists(filePath))
{
// Create the path for the new file by appending ".inv" to the original file name
string invertedFilePath = Path.ChangeExtension(filePath, ".inv");
try
{
// Open the original file for reading in binary mode
using (FileStream inputFile = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
// Get the length of the file
long fileLength = inputFile.Length;
// Open the new file for writing in binary mode
using (FileStream outputFile = new FileStream(invertedFilePath, FileMode.Create, FileAccess.Write))
{
// Loop through the original file from the last byte to the first byte
for (long i = fileLength - 1; i >= 0; i--)
{
// Move the read position to the current byte in the input file
inputFile.Seek(i, SeekOrigin.Begin);
// Read the byte at the current position
byte[] byteToWrite = new byte[1];
inputFile.Read(byteToWrite, 0, 1);
// Write the byte to the output file
outputFile.Write(byteToWrite, 0, 1);
}
}
}
// Inform the user that the file has been successfully inverted
Console.WriteLine("The binary file has been successfully inverted.");
}
catch (Exception ex) // Catch any errors that occur
{
// Output an error message if an exception is thrown
Console.WriteLine("An error occurred: " + ex.Message);
}
}
else
{
// Inform the user if the specified file doesn't exist
Console.WriteLine("The specified file does not exist.");
}
}
}