I have text files like csv format each with different csv formats.
Example:
-
Value1,value2,Value3
-
“Val1″,”val2″,”val3”
-
“value1″,Value2,Value3,”Value4”
-
“Value”,”Value1,Value2″,”Value3″
I need a standard code to push these datas to correct column headers in datatable.
Currently I have read the text file using streamreader and write the headers in datatable and then by foreach loop will insert all the rows in the datatable.
At first I split the columns based on comma.
But the format with double quotes (EXAMPLE 4) in a single column getting error(Input array is longer than the number of columns in this table.), so I coded with if else, if the column has double quotes, it will go to if condition, else it will go to else condition as the code below, But this affects Example3
As it inserts the value as
Expected Output:
My Code:
DataTable csvData = new DataTable();
string[] lines = File.ReadAllLines(D:FilepathFilename.txt);
foreach (string line in lines)
{
if (line.Contains("""))
{
col = line.Split('"');
col = Array.FindAll(col, isNotCommaHeader).ToArray();
col = col.Skip(1).ToArray();
col = col.Take(col.Count() - 1).ToArray();
}
else
{
col = line.Split(',');
}
csvData.Rows.Add(col);
}
Can anyone have idea how to insert all those formats in datatable?
5