Reading comma separated values for a CSV file

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


Share this post   Email it

Feedback

Posted on 2/1/2007 7:04:44 AM

thanks for sharing this needful one Vikram.
Keep sharing.

Posted on 10/16/2007 10:54:29 PM

thanks for giving me the idea to fetch data from csv file and insert them to dataseT

Posted on 10/19/2007 4:36:33 AM

Dude I love for this.... you saved my life.....

Posted on 10/29/2007 3:21:54 AM

Hi vikram sir

You had posted a great code but in this you had filling the dataadaptor but here i'm in a situation in need to populate the generic list as i also need to validate the data. So please give me the brief idea abut that.

Thanks

Posted on 11/5/2007 6:14:22 AM

Thanks for this article this was very helpful
Thanks

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 

Copyright © 2006 - 2010 Vikram Lakhotia