Grupo
Manejo de archivos en C#
Objectivo
1. El usuario proporcionará el nombre del archivo que se va a invertir.
2. El programa abrirá el archivo original usando FileStream para leer sus bytes.
3. El programa creará un nuevo archivo con el mismo nombre que el original, pero con la extensión .inv.
4. Escribirá los bytes del archivo original en el nuevo archivo en orden inverso.
5. Tras completar el proceso, el programa mostrará un mensaje indicando que la operación se ha realizado correctamente.
Cree un programa para "invertir" un archivo usando un "FileStream". El programa debe crear un archivo con el mismo nombre, terminado en ".inv", que contenga los mismos bytes que el archivo original, pero en orden inverso. El primer byte del archivo resultante debe ser el último byte del archivo original, el segundo byte el penúltimo, y así sucesivamente hasta el último byte del archivo original, que debe aparecer en la primera posición del archivo resultante.
Ejemplo de ejercicio en C#
Mostrar código C#
using System;
using System.IO;
class FileInverter
{
// Main method to run the program
static void Main(string[] args)
{
// Ask the user for the name of the file to invert
Console.WriteLine("Please enter the name of the file to invert:");
// Read the file name from user input
string fileName = Console.ReadLine();
try
{
// Check if the file exists
if (!File.Exists(fileName))
{
Console.WriteLine("Error: The specified file does not exist.");
return;
}
// Create a FileStream to read the original file
using (FileStream inputFile = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
// Create a FileStream to write the inverted file with ".inv" extension
using (FileStream outputFile = new FileStream(fileName + ".inv", FileMode.Create, FileAccess.Write))
{
// Get the total length of the original file
long fileLength = inputFile.Length;
// Loop through the original file in reverse order
for (long i = fileLength - 1; i >= 0; i--)
{
// Move the stream position to the current byte to read
inputFile.Seek(i, SeekOrigin.Begin);
// Read the byte at the current position
int byteValue = inputFile.ReadByte();
// Write the byte to the new file in reverse order
outputFile.WriteByte((byte)byteValue);
}
}
}
// Inform the user that the inversion is complete
Console.WriteLine($"The file '{fileName}' has been successfully inverted and saved as '{fileName}.inv'.");
}
catch (Exception ex)
{
// Handle any errors that may occur during the process
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
Output
//If the user enters example.txt and the file contains the following bytes:
Hello, world!
//The program will create a file named example.txt.inv with the reversed content:
!dlrow ,olleH
Código de ejemplo copiado
Comparte este ejercicio de C#