Hi
Yesterday I was working with some data and found the requirement to work with the CSV files. Al I had to do was read some CSV files. To read the CSV file I had to use Microsoft.Jet.OLEDB.4.0 provider.
I created a function that would take the file path as a parameter and return a dataset containing the table structure of the CSV file. Now the user can do what ever he wants to with this dataset. The function was something like this.
public DataSet getDataSet(string FilePath)
{
DataSet ds=new DataSet();
string ConnectionString, CommandText;
OleDbConnection conn ;
OleDbCommand Command;
ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Path.GetDirectoryName(FilePath) + ";Extended Properties='text;HDR=Yes'";
CommandText = "select * from " + Path.GetFileName(FilePath);
conn = new System.Data.OleDb.OleDbConnection(ConnectionString);
Command = new System.Data.OleDb.OleDbCommand(CommandText, conn);
conn.Open();
System.Data.OleDb.OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter(CommandText, conn);
da.Fill(ds);
return ds;
}
Here the function takes a string parameter FilePath. This has to be the absolute path of the file. We then get the Directory name of the file by using the Path.GetFileName() function and create the connection string to the File. We select all the data from the file and fill that in a dataset using the dataadapter.fill method. That’s all we need to do to get the data from a csv file.
Hope this helps
Thanks
Vikram