Ejercicio
Conversor CSV
Objetivo
El CSV ("Valores separados por comas") es un formato de intercambio utilizado por muchas hojas de cálculo y bases de datos de sistemas de gestión. Es una serie de valores separados por comas encerrados entre comillas, aunque hay variantes que no usan comillas, o que usan punto y coma como separador. A menudo las cifras no están entre comillas. Un archivo de ejemplo sería:
"Juan", "López Pérez", "Alicante", 25
"Antonio", "Pérez López", "Madrid", 27
Debe crear un programa que lea un archivo CSV como el anterior, con cuatro bloques de datos (los primeros 3 son de texto y el último será numérico), cada uno de los cuales está en una línea, y generar un archivo de texto cada entrada contiene una línea como esta:
John
Pérez López
Alicantino
25
Anthony
Pérez López
Madrid
27
Código de Ejemplo
// Import necessary namespaces for file handling
using System; // Basic input/output operations
using System.IO; // FileStream and StreamReader for reading and writing files
using System.Text; // StringBuilder for efficient string handling
class CSVConverter // Main class for the CSV conversion program
{
static void Main(string[] args) // Entry point of the program
{
// Check if the correct number of arguments (input and output files) are provided
if (args.Length != 2) // If not enough arguments are provided
{
Console.WriteLine("Usage: CSVConverter "); // Show usage instructions
return; // Exit the program if the arguments are incorrect
}
string inputFile = args[0]; // The input CSV file name
string outputFile = args[1]; // The output text file name
// Check if the input CSV file exists
if (!File.Exists(inputFile)) // If the input file does not exist
{
Console.WriteLine("Error: The input CSV file does not exist."); // Inform the user about the missing file
return; // Exit the program if the input file is missing
}
try
{
// Open the input CSV file for reading
using (StreamReader reader = new StreamReader(inputFile)) // StreamReader to read the CSV file
{
// Create the output text file for writing
using (StreamWriter writer = new StreamWriter(outputFile, false, Encoding.UTF8)) // StreamWriter to write the text file
{
string line; // Variable to store each line from the CSV file
// Read the CSV file line by line
while ((line = reader.ReadLine()) != null) // Continue until the end of the file
{
// Remove leading and trailing spaces from each line
line = line.Trim();
// Split the line by comma and remove any surrounding quotes
string[] parts = line.Split(','); // Split the line into parts based on commas
// Clean up quotes around each part
for (int i = 0; i < parts.Length; i++)
{
parts[i] = parts[i].Trim('"'); // Remove quotes from each part
}
// Write each part to the output file on a separate line
foreach (string part in parts) // Loop through each part of the line
{
writer.WriteLine(part); // Write each part to a new line in the output file
}
}
}
}
Console.WriteLine("CSV file has been successfully converted to text format."); // Inform the user that the conversion is complete
}
catch (Exception ex) // Catch any exceptions that occur during the file reading or writing process
{
Console.WriteLine($"An error occurred: {ex.Message}"); // Display the error message
}
}
}