Ejercicio
Invertir archivo binario V2
Objetivo
Crear un programa para "invertir" un archivo, utilizando un "FileStream": crear un archivo con el mismo nombre que termine en ".inv" y que contenga los mismos bytes que el archivo original pero en orden inverso (el primer byte será el último, el segundo será el penúltimo, y así sucesivamente, hasta el último byte del archivo original, que debe aparecer en la primera posición del archivo resultante).
Debe entregar solo el archivo ".cs", que debe contener un comentario con su nombre
Código de Ejemplo
// 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.");
}
}
}