Ask Your Question
2

How can we use C# to parse CSV files using OleDb?

asked 2023-07-19 07:04:19 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-19 07:25:01 +0000

ladyg gravatar image

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();
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-19 07:04:19 +0000

Seen: 16 times

Last updated: Jul 19 '23