Grupo
Manejo de archivos en C#
Objectivo
1. El programa lee un archivo binario byte a byte.
2. Filtra los caracteres cuyos códigos ASCII no estén entre 32 y 127, o sean iguales a 10 o 13.
3. Los caracteres alfabéticos extraídos se escriben en un nuevo archivo de texto.
4. El programa gestiona errores como archivos de entrada faltantes o problemas con la escritura de archivos.
Ejemplo de uso:
extractAlphaChars inputFile.bin outputFile.txt
Cree un programa que extraiga solo los caracteres alfabéticos contenidos en un archivo binario y los guarde en un archivo aparte. Los caracteres extraídos deben ser aquellos cuyo código ASCII esté entre 32 y 127, o sea igual a 10 o 13.
Ejemplo de ejercicio en C#
Mostrar código C#
using System;
using System.IO;
class AlphabeticExtractor
{
// Main method where the program starts execution
static void Main(string[] args)
{
// Check if the user provided the input and output filenames as command line arguments
if (args.Length != 2)
{
Console.WriteLine("Usage: extractAlphaChars ");
return;
}
// Get the input and output file paths from the command line arguments
string inputFile = args[0];
string outputFile = args[1];
try
{
// Open the input binary file for reading
using (FileStream input = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
{
// Open the output text file for writing
using (StreamWriter output = new StreamWriter(outputFile))
{
// Read the file byte by byte
int byteRead;
while ((byteRead = input.ReadByte()) != -1)
{
// Check if the byte is a printable character or line feed/carriage return
if ((byteRead >= 32 && byteRead <= 127) || byteRead == 10 || byteRead == 13)
{
// Write the printable character to the output file
output.Write((char)byteRead);
}
}
}
}
Console.WriteLine("Alphabetic characters have been extracted to " + outputFile);
}
catch (Exception ex)
{
// If there was an error, display the error message
Console.WriteLine($"Error: {ex.Message}");
}
}
}
Output
//Case 1 - Successful Extraction:
//For the command:
extractAlphaChars inputFile.bin outputFile.txt
//Output:
Alphabetic characters have been extracted to outputFile.txt
//Case 2 - Error (File Not Found):
//For the command:
extractAlphaChars nonExistentFile.bin outputFile.txt
//Output:
Error: The system cannot find the file specified.
Código de ejemplo copiado
Comparte este ejercicio de C#