Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To parse CSV files using OleDb in C#, you can follow these steps:

  1. Create an instance of the OleDbConnection class and pass the connection string. The connection string should include the path of the CSV file and the required properties of the OleDb provider.
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=filepath;Extended Properties=\"Text;HDR=YES;FMT=Delimited\"";
OleDbConnection conn = new OleDbConnection(connectionString);
  1. Open the connection.
conn.Open();
  1. Create an instance of the OleDbCommand class and pass the SQL query.
string query = "SELECT * FROM [filename.csv]";
OleDbCommand cmd = new OleDbCommand(query, conn);
  1. Create an instance of the OleDbDataAdapter class and pass the OleDbCommand and OleDbConnection objects.
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
  1. Create a DataSet object and call the Fill method of the OleDbDataAdapter object to populate the DataSet with the CSV data.
DataSet ds = new DataSet();
adapter.Fill(ds);
  1. You can access the data in the DataSet and iterate through the rows and columns to perform further processing.
foreach (DataRow row in ds.Tables[0].Rows)
{
    Console.WriteLine(row[0].ToString() + " " + row[1].ToString() + " " + row[2].ToString());
}
  1. Close the OleDbConnection.
conn.Close();