8.30 - CSV converter

Objetive

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

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

It should create a program that reads a CSV file as above, with four data blocks (the first 3 are text and the last will be numeric), each of which is in a line, and generate a text file each entry contains a line like this:

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


Solution

using System;
using System.IO;
namespace ReaderCSV
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("CSV READER");
            Console.WriteLine("--------------------------------------");
            Console.Write("Enter name of file .csv: ");
            
            string nameFile = Console.ReadLine();
            StreamReader myfile;
            string cadena;
            int position;

            try
            {
                myfile = new StreamReader(nameFile, System.Text.Encoding.Default);
                string line;
                do
                {
                    line = myfile.ReadLine();
                    if ((line != null) && (line != ""))
                    {
                        try
                        {
                            line = line.Replace("\"", "");

                            position = line.IndexOf(';');
                            cadena = line.Substring(0, position);
                            line = line.Remove(0, position + 1);
                            Console.WriteLine(cadena + "\n");

                            position = line.IndexOf(';');
                            cadena = line.Substring(0, position);
                            line = line.Remove(0, position + 1);
                            Console.WriteLine(cadena + "\n");

                            position = line.IndexOf(';');
                            cadena = line.Substring(0, position);
                            line = line.Remove(0, position + 1);
                            Console.WriteLine(cadena + "\n");

                            cadena = line.Substring(0);
                            Console.WriteLine(cadena + "\n"); 
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Error !!! " + e.Message);
                        }
                    }
                }
                while (line != null);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error !!!" + e.Message);
            }
        }
    }
}


Popular Posts