Home > Back-end >  Reading csv without specific type
Reading csv without specific type

Time:06-24

I want to read csv file and save to list or array or anything, but CsvHelper demands to save it as collection of specific type. Problem is my csv has so many columns, that mapping it to custom class will take a few weeks.

How can I just read it without saving as specific type? Accessing specific values with thing like row[1][2] is more than enough for me.

CodePudding user response:

Add it to a datatable

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


namespace ConsoleApplication23
{

    class Program
    {
        const string FILENAME = @"c:\temp\test.csv";
        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(FILENAME);
            string line = "";
            DataTable dt = new DataTable();
            int rowCount = 0;
            while((line = reader.ReadLine()) != null)
            {
                line = line.Trim();
                if (line.Length > 0)
                {
                    string[] splitArray = line.Split(new char[] { ',' });
                    if (rowCount == 0)
                    {
                        foreach (string col in splitArray)
                        {
                            dt.Columns.Add(col, typeof(string));
                        }
                    }
                    else
                    {
                        dt.Rows.Add(splitArray);
                    }
                }

            }
 

        }
    }
 
}
  • Related