Feb 4, 2008

5 minutes C# code to load CSV file into a DataSet


Step 1 : add button for browsing files, a textbox to hold the file name and paste the followin code in the browse button click handler (this code will basically popup a OpenFileDialog, set up to only open files with .csv extension):

             OpenFileDialog ofd = new OpenFileDialog ();
            ofd.Filter =
"CSV Files|*.csv" ;
            
if (ofd.ShowDialog() == DialogResult .OK)
            {
               
this .textBox2.Text = ofd.FileName;
                GetData();
            }

Then we need to get the file from the textbox2 and load it into data set:

      
private void GetData()
       {
            
FileInfo fi = new FileInfo (textBox2.Text);
            
OleDbConnection con = new OleDbConnection ( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fi.Directory.FullName + ";Extended Properties='text;HDR=Yes;FMT=Delimited'" );
            con.Open();

            
DataSet dsThings = new DataSet ();
            
OleDbCommand cmd = new OleDbCommand ( "SELECT * FROM " + fi.Name, con);
            
OleDbDataAdapter adapt = new OleDbDataAdapter (cmd);
            adapt.Fill(dsThings);
            
this .dataGridView1.DataSource = dsThings.Tables[0];
            
       }

As you can see we use OleDB provider to load the CSV file into the dataset.

No comments: