Click here to Skip to main content
15,940,921 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

I am looking to achieve the following; I have a CSV file that I want to read into a DataTable object. The only thing I know about the file is that the first row contains header names and that the various columns are either of the type double, of the type int or of the type string (or actually an element of an enumwith possible values the set of unique strings in the column). The question is, how to create a datatable in which each column has the right type?

Basically my set-up looks like:

private char[] inputDelimiter = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator.ToCharArray();
private DataTable output = new DataTable();

using( StreamReader myReader = new StreamReader(fileName) )
                string[] varNames = myReader.ReadLine().Split(inputDelimiter);
                for (int colCntr = 0; colCntr < varNames.Length; colCntr++)
                     output.Columns.Add(new DataColumn(varNames[colCntr]));

                // code needed here to determine the data type of each column;

                string nextLine;
                while ( (nextLine = myReader.ReadLine()) != null )
                    // I'll fill the datatable here myself


Any thoughts are greatly appreciated.

1 solution

Use int.TryParse, then double.TryParse to work out if the data is a double, or an int, then after that, you can assume it's just a string.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900