Hi friends,
I am facing problem while reading file .csv into datatable. if first value of coulumn is numeric it treats the column datatype as neumeric and doesn't read coulmns value further if in string type. It reads only neumeric values.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Saillesh PawarPosted Dec 13, 2015, 3:06 PM
DataSet dsdata = ConvertCSVFile1(FileName, fileinfo.Name, "MyNewTable", "\t");
private DataSet ConvertCSVFile1(string target1, string fileName, string TableName, string delimiter)
{
System.Data.DataSet result = new DataSet();
StreamReader s = new StreamReader(target1);
string[] columns = s.ReadLine().Split(',');
result.Tables.Add(TableName);
foreach (string col in columns)
{
bool added = false;
string next = "";
int i = 0;
while (!added)
{
string columnname = col + next;
columnname = columnname.Replace("#", "");
columnname = columnname.Replace("'", "");
columnname = columnname.Replace("&", "");
if (!result.Tables[TableName].Columns.Contains(columnname))
{
result.Tables[TableName].Columns.Add(columnname);
added = true;
}
{
i++;
next = "_" + i.ToString();
}
}
}
try
{
string AllData = s.ReadToEnd().Replace("\r", "").Replace("||", "|");
string[] rows = AllData.Split("\n".ToCharArray());
foreach (string r in rows)
{
string[] items = r.Split(',');
result.Tables[TableName].Rows.Add(items);
}
}
catch (Exception ex)
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
lblMsg.Text = "Line: " + trace.GetFrame(0).GetFileLineNumber();
}
s.Close();
return result;
}