Thursday 21 February 2013

Read CSV File Using C# ASP.Net

Read CSV File Using C# ASP.Net

In this article we will see how we can fetch data from a CSV file and can export it to a DataReader so that we can show it row by row.. Here is how it works:

First you have to declare two string variables and their properies for store directory and filename of csv file which you want to extract data.

private string dirCSV;
private string fileNevCSV;

public string FileNevCSV
 get{return fileNevCSV;}

public string dirCSV
 get{return dirCSV;}

In the second step connect to the data source and fill it to the dataset.

public DataSet loadCVS(int noofrows)
            DataSet ds = new DataSet();
                // Creates and opens an ODBC connection
                string strConnString = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + this.dirCSV.Trim() + ";Extensions=asc,csv,tab,txt;Persist Security Info=False";
                string sql_select;
                OdbcConnection conn;
                conn = new OdbcConnection(strConnString.Trim());

                //Creates the select command text
                if (noofrows == -1)
                    sql_select = "select * from [" + this.FileNevCSV.Trim() + "]";
                    sql_select = "select top " + noofrows + " * from [" + this.FileNevCSV.Trim() + "]";

                //Creates the data adapter
                OdbcDataAdapter obj_oledb_da = new OdbcDataAdapter(sql_select, conn);

                //Fills dataset with the records from CSV file
                obj_oledb_da.Fill(ds, "csv");

                //closes the connection

            catch (Exception e) //Error

            return ds;


In the third step extract data to DataTable from generated DataSet.

this.dirCSV = "file path";
this.fileNevCSV ="file name";
DataSet ds = loadCVS(-1);
DataTable table = ds.Tables[0];

foreach (DataRow row in table.Rows)
//iterate through the DataTable.


No comments:

Post a Comment

Thank You for Your Comments. We will get back to you soon.

back to top