public DataTable ParseToDataTable(string path)
{
reader = new StreamReader(path);
DataTable result = new DataTable();
result.TableName = "CSV";
int DeduceRowCount = 5;//rows of data to read for deducing data type
string line = "";
int read_row_count=0;
//header
string header = reader.ReadLine();
string[] column_names = BreakCSV(header);
List<string> DeduceRows = new List<string>();
List<int> ColTypes = new List<int>();
for (int i = 0; i < column_names.Length; i++)
ColTypes.Add(0);
//Deduction codes:
//Not Set=0
//String=1
//Int32=2
//Double=3
//need to read the first DeduceRowCount lines and deduce types of each column
while (!reader.EndOfStream && read_row_count<DeduceRowCount)
{
line = reader.ReadLine();
read_row_count++;
DeduceRows.Add(line);
string[] data = BreakCSV(line);
int col_type = 0;
int test_int=0;
double test_double=0.0;
for (int i = 0; i < data.Length;i++)
{
string entry = data[i];
col_type = 1;
try
{
test_int = Convert.ToInt32(entry);
col_type = 2;
}
catch
{//Conversion to Int32 failed, could be Double or string
try
{
test_double = Convert.ToDouble(entry);
col_type = 3;
}
catch
{//Conversion to Double failed, can only be a string at this point
}
}
ColTypes[i] = Math.Max(col_type, ColTypes[i]);//If we currently have int, but previously had Double, then make sure we remember that
}
}
//Add the column to the DataTable, with its associated type
for (int i=0;i<ColTypes.Count;i++)
{
DataColumn column;
switch(ColTypes[i])
{
case 2:
column = new DataColumn(column_names[i], typeof(Int32));
break;
case 3:
column = new DataColumn(column_names[i], typeof(Double));
break;
default:
column = new DataColumn(column_names[i], typeof(String));
break;
}
column.ColumnMapping = MappingType.Attribute;
result.Columns.Add(column);
}
//Now add the DeduceRows to DataTable before moving on
foreach(string deduced_line in DeduceRows)
{
string[] data = BreakCSV(deduced_line);
int i = 0;
DataRow dr = result.NewRow();
foreach (string d in data)
{
dr[i++] = d;
}
result.Rows.Add(dr);
}
//Now read the remainder of the data
while (!reader.EndOfStream)
{
line = reader.ReadLine();
string[] data = BreakCSV(line);
int i = 0;
DataRow dr = result.NewRow();
foreach (string d in data)
{
dr[i++] = d;
}
result.Rows.Add(dr);
}
reader.Close();
return result;
}
}