C# read csv file

C# read csv file

C# Read CSV File

   Some one told me to write a program which reads csv file. Well the code is very simple and easy to understand.
To read CSV file you can use class OledbProvider found under System.Data.Oledb namespace.

You can refer
www.connectionstrings.com for connection string required to open your CSV file.

You can execute query like [ select * from xyz ] syntax on CSV file.

I have created xxx.csv file on local D:\ drive.

After excuting below code you will get all data into data table where you can do further processing.
You can bind datatable to GridView or iterate through the data or filter the data.

Following are the contents of my xxx.csv file.

"First Name", "Last Name"
"Satalaj", "More"
"Rod","Jhonson"
"Shane","Glover"

And here is my code

private void Form1_Load(object sender, EventArgs e)
        {


            // Prepare cnnection string
 

            string connectionstring = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\;Extended Properties='text;HDR=Yes;FMT=Delimited';";

           // Create connection object

            OleDbConnection connection = new OleDbConnection();

           // Assign connection to connection object

            connection.ConnectionString = connectionstring;
          
           // Prepare command object
          
            OleDbCommand command = new OleDbCommand();
            command.CommandType = CommandType.Text;

           // Tell command object to use connection object 


            command.Connection = connection;

           // prepare command statement

            command.CommandText = "select * from [xxx.csv]";

          // Open connection with your csv file

            connection.Open();

          // create data table object            

             DataTable dt = new DataTable();

         // Execute Reader and load the data into datatable

            dt.Load(command.ExecuteReader());

             // Close the connection

            connection.Close();

           
        }


Description
At connection string HDR=Yes means first row of CSV file contains header (coloumn) information of your table.


 


-Satalaj 

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Author

code tutorial