CSV Converter - C# Programming Exercise

This exercise involves creating a program that reads a CSV file with four data blocks (three text fields and one numeric) separated by commas, and generates a text file where each entry is organized into separate lines. The input CSV file contains data of individuals, and the program needs to process this data and reformat it into the requested format. This exercise helps in understanding how to handle CSV files and how to process and organize data into a text file. The use of commas as delimiters is key in processing data in CSV format, and this exercise reinforces the understanding of this data exchange format between systems.

 Category

File Management

 Exercise

CSV Converter

 Objective

The CSV ("Comma Separated Values") is an exchange format used by many spreadsheet and database management systems. It consists of a series of comma-separated values enclosed in quotation marks, although there are variants that do not use quotes or use semicolons as separators. Often, the values are not enclosed in quotes. An example file would be:

"John", "López Pérez," "Alicante", 25
"Antonio", "Pérez López", "Madrid", 27

You should create a program that reads a CSV file as shown above, with four data blocks (the first three are text and the last one is numeric), each of which is on a separate line. The program should generate a text file where each entry contains a line like this:

John
Pérez López
Alicante
25
Antonio
Pérez López
Madrid
27

 Write Your C# Exercise

// 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
        }
    }
}

 Share this C# exercise

 More C# Programming Exercises of File Management

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  File comparer

    This exercise involves creating a C# program that determines if two files (of any kind) are identical, meaning they have the same content. The program should c...

  •  Display BPM on console

    This exercise involves creating a C# program to decode an image file in the Netpbm format (specifically, the P1 format, which is for black and white ima...

  •  PCX width and height

    This exercise involves creating a C# program to check if a file is a PCX image and, if so, extract and display the image's dimensions (width and height). To do...

  •  Extract text from a binary file

    This exercise involves creating a C# program that extracts only the alphabetic characters contained in a binary file and dumps them to a separate file. The program sh...

  •  C# to Pascal converter

    This exercise involves creating a C# program that converts simple C# programs to their equivalent in the Pascal language. The program should read C# cod...

  •  Dump

    This exercise involves creating a "dump" utility: a hex viewer that displays the contents of a file, with 16 bytes per row and 24 rows per screen. The program should pause a...