Tuesday, May 15, 2012

Reading CSV file and Displaying Data

In this article I am going to explain about how to read the comma separated value file and how to display the values. one of my application I got this requirement Reading CSV file and displaying Data.
CSV stands for Comma Separated Values, sometimes also called Comma Delimited. A CSV file is a specially formatted plain text file which stores spreadsheet or basic database-style information in a very simple format, with one record on each line, and each field within that record separated by a comma.
Let us create a sample CSV file with the following Data and having the columns ID,FirstName,LastName and save this file as 1.csv
The following figure will give the CSV file that I have used in the program.

Then after designing the CSV create a console application and add the following namespace .
using System.IO;
ReadAllLines method can be used to read the contents of a CSV file to array. Each line of the text file will become the elements of the array. ReadAllLines method opens a text file, reads all lines of the file into a string array, and then closes the file.
Then write the following code to read the CSV.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
           ReadFile("C:\\Documents and Settings\\Administrator\\Desktop\\1.csv");
        }

        public static void ReadFile(string Filepath)
        {
            string[] Filecontent = File.ReadAllLines(Filepath);
            int lno = 0;
            foreach (string line in Filecontent)
            {
                string[] Linevalues = line.Split(',');
                Console.WriteLine("Line  : " + lno.ToString() + "values are as follows");
                Console.WriteLine("______________________________________");
                Console.WriteLine("ID : "+ Linevalues[0].ToString());
                Console.WriteLine("First Name : "+ Linevalues[1].ToString());
                Console.WriteLine("Last Name : "+ Linevalues[2].ToString());
                Console.WriteLine("______________________________________");
                lno = lno + 1;
            }
            Console.ReadKey();
        }
    }
}

Output:

No comments:

Post a Comment