Ejercicio
Extraer texto de un archivo binario
Objetivo
Cree un programa para extraer (sólo) los caracteres alfabéticos contenidos en un archivo binario y volcarlos a un archivo diferente. Los caracteres extraídos deben ser aquellos cuyo código ASCII sea 32 a 127, o 10, o 13.
Código de Ejemplo
// Import the necessary namespaces for file handling and basic input/output operations
using System;
using System.IO;
// Declare the main Program class
class Program
{
// Main method where the program starts
static void Main()
{
// Specify the input binary file and output text file paths
string inputFilePath = "input.bin"; // Replace with the path to your binary file
string outputFilePath = "output.txt"; // Replace with the desired output file path
// Try to process the binary file and extract printable characters
try
{
// Open the input binary file using a BinaryReader
using (BinaryReader reader = new BinaryReader(File.Open(inputFilePath, FileMode.Open)))
{
// Create a StreamWriter to write the extracted characters to the output file
using (StreamWriter writer = new StreamWriter(outputFilePath))
{
// Read the entire file byte by byte
while (reader.BaseStream.Position < reader.BaseStream.Length)
{
// Read the next byte from the file
byte b = reader.ReadByte();
// Check if the byte represents an ASCII character between 32 and 127, or is 10 (newline) or 13 (carriage return)
if ((b >= 32 && b <= 127) || b == 10 || b == 13)
{
// Write the character to the output file
writer.Write((char)b);
}
}
}
}
// Notify the user that the extraction was successful
Console.WriteLine($"Extracted text has been saved to '{outputFilePath}'");
}
catch (Exception ex) // Catch any errors that may occur during file reading or writing
{
// Print the error message to the console
Console.WriteLine($"Error processing the file: {ex.Message}");
}
}
}