Thursday, August 23, 2012

Read CSV file in C#

Below is the C# code to read the data from CSV file to DataTable.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using Microsoft.VisualBasic.FileIO;


public DataTable ReadCSVData(StreamReader reader)
{
    DataTable dtReadFileData =  null;
    try
    {
         TextFieldParser parser = new TextFieldParser(reader);
         dtReadFileData = new DataTable();
         parser.TextFieldType = FieldType.Delimited;
         parser.SetDelimiters(",");
         String[] stringRow = parser.ReadFields();

         foreach(String field in stringRow)
         {
             dtReadFileData.Columns.Add(field, Type.GetType("System.String"));
         }

         while(!parser.EndOfData)
         {
             stringRow = parser.ReadFields();
             dtReadFileData.Rows.Add(stringRow);
         }

         return dtReadFileData;
    }

    catch(Exception ex)
    {
         //Handle the exception
    }
}

No comments:

Post a Comment