C # Reading CSV files
Many projects need to operate the CSV file. I see many people will code to read the first row of the CSV file and explain the values of each column,
This is relatively difficult,
First, developers are required to be familiar with string processing,
Second, we need to have a good understanding of the CSV file structure, which is difficult and the quality of the Code to be written must be tested for a period of time,
But there is actually a simpler method, that is, using Microsoft's text driver to access CSV files in the form of tables.
The Code is as follows:
Public DataTable GetCsvData (string filePath, string fileName)
{
String path = filePath + "\" + fileName + ". csv ";
String connString = @ "Driver = {Microsoft Text Driver (*. txt; *. csv)}; Dbq =" + filePath + "; Extensions = csv ";
Try
{
Using (OdbcConnection odbcConn = new OdbcConnection (connString ))
{
OdbcConn. Open ();
OdbcCommand oleComm = new OdbcCommand ();
OleComm. Connection = odbcConn;
OleComm. CommandText = "select * from [" + fileName + "# csv]";
OdbcDataAdapter adapter = new OdbcDataAdapter (oleComm );
DataSet ds = new DataSet ();
Adapter. Fill (ds, fileName );
OdbcConn. Close ();
Return ds. Tables [0];
}
}
Catch (Exception ex)
{
Throw ex;
}
}