peter
peter

Reputation: 8652

Read CSV file in C# and store in DataTable

I am using following code to read csv file and store in to C#. But my requirement is that, I want to skip the first line in csv file, since it is not structured, hence take the second row as column. How to do it in the exiting code.

private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{    
   DataTable csvData = new DataTable();

    try
    {

    using(TextFieldParser csvReader = new TextFieldParser(csv_file_path))
        {
            csvReader.SetDelimiters(new string[] { ";" });
            csvReader.HasFieldsEnclosedInQuotes = true;
            string[] colFields = csvReader.ReadFields();
            foreach (string column in colFields)
            {
                DataColumn datecolumn = new DataColumn(column);
                datecolumn.AllowDBNull = true;
                csvData.Columns.Add(datecolumn);
            }

            while (!csvReader.EndOfData)
            {
                string[] fieldData = csvReader.ReadFields();
                //Making empty value as null
                for (int i = 0; i < fieldData.Length; i++)
                {
                    if (fieldData[i] == "")
                    {
                        fieldData[i] = null;
                    }
                 }
                     csvData.Rows.Add(fieldData);
             }
        }
   }
   catch (Exception ex)
   {
   }
   return csvData;
}

My CSV file looks like

a;;{b;g;t{}
firstname;lastname;age;locaion
peter;vela;28;denver
sasi;kiran;38;colorado
sastri;miro;texas

Upvotes: 0

Views: 9608

Answers (4)

string[] Lines = File.ReadAllLines(this.INPUTTFILE);
string[] Fields;
for (int i = 1; i < Lines.GetLength(0); i++)
{
    DataRow Row = Dt_Input_With_ColoumName.NewRow();
    Fields = Lines[i].Split(new char[] { ',' });
    for (int f = 0; f < Dt_Input_With_ColoumName.Columns.Count; f++)
    {
        Row[f] = Fields[f];
    }
    Dt_Input_With_ColoumName.Rows.Add(Row);
}

Upvotes: 0

Tabish Matin
Tabish Matin

Reputation: 85

If you want to make your life easy and ready to spend some money. Flexcel will make your life easy.

This thing will be done in 2 lines of code.

Thanks

Upvotes: 0

Dennis
Dennis

Reputation: 346

This should work:

int rowsToSkip = 1;
int position = 0;
while (!csvReader.EndOfData)
{
    string[] fieldData = csvReader.ReadFields();
    if(position >= rowsToSkip)
    {

        //Making empty value as null
        for (int i = 0; i < fieldData.Length; i++)
        {
            if (fieldData[i] == "")
            {
                fieldData[i] = null;
            }
        }
        csvData.Rows.Add(fieldData);
    }
    position++;
}

Upvotes: 0

Steve
Steve

Reputation: 216243

The TextFieldParser class has a constructor that can receive a stream.
So the idea is: Open a StreamReader on your file, read the first line and discard it, then build the TextFieldParser with the opened StreamReader positioned on the second line where your column names exist.

I have tested it and it seems to work

using (StreamReader reader = new StreamReader(csv_file_path))
{
    // Discard the first line... (add checking here)
    reader.ReadLine();
    using(TextFieldParser csvReader = new TextFieldParser(reader))
    {
       csvReader.SetDelimiters(new string[] { ";" });
       .....

I have also set the delimiter to a semicolon instead of a comma according to your sample data.

Upvotes: 1

Related Questions