In many systems, you need to read CSV files. I have encountered in a previous project that reads data from the CSV file to the datatable for processing.Code
The method I previously wrote to import the data in the CSV file to the able. Now I will post it to share with you:
// Getcsvfile's filename and data get the data in the CSV file and import the data into the able
// Mycsvdt is used to hold the data datatable In the CSV file. filepath refers to the path of the CSV file.
Private bool opencsvfile (ref datatable mycsvdt, string filepath)
{
String strpath = filepath; // path of the CSV file
Try
{
Int intcolcount = 0;
Bool blnflag = true;
Datacolumn mydc;
Datarow mydr;
String strline;
String [] aryline;
Streamreader mysr = new streamreader (strpath, system. Text. encoding. Default );
While (strline = mysr. Readline ())! = NULL)
{
Aryline = strline. Split (New char [] {','});
// Add the column name to the datatable
If (blnflag)
{
Blnflag = false;
Intcolcount = aryline. length;
Int Col = 0;
For (INT I = 0; I <aryline. length; I ++)
{
Col = I + 1;
Mydc = new datacolumn (Col. tostring ());
Mycsvdt. Columns. Add (mydc );
}
}
// Fill in the data and add it to the able
Mydr = mycsvdt. newrow ();
For (INT I = 0; I <intcolcount; I ++)
{
Mydr [I] = aryline [I];
}
Mycsvdt. Rows. Add (mydr );
}
Return true;
}< br> catch (exception e)
{< br>
throw (stack. geterrorstack (strpath + "error in reading CSV file data. "+ E. message, "opencsvfile (");
return false;
}< BR >}