Wednesday, December 14, 2011

Reading .CSV file to DataSet in C#



Pre-Requisites (if you are using 64 bit CPU mode in IIS 7.0

Following code snippet is using Microsoft .Jet.OLEDB.4.0 to read the data from .CSV file. As 64 version of Microsoft.Jet.OLEDB.4.0 is not available, it will throw following exception while running on 64 bit CPU mode in IIS 7.0.


Microsoft .Jet.OLEDB.4.0 not registered on the Local Machine.

Fix – We have to run the Application Pool in "Enable 32 bit Application mode" in IIS7 manager using following steps

1. Right click on the Application Pool and select “Advanced Settings…” or select the same from the Actions pane after selecting the Application pool
2. Change the “Enable 32-bit Applications” to True (if you want the application pool to spawn in a 32-bit mode)
3. Click OK



public static DataSet ReadCSVFile(string directoryName, string filename)
{
string connString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Text;HDR=Yes;FMT=Delimited;IMEX=1;\"", directoryName);
string cmdString = string.Format("SELECT * FROM [{0}]", filename);
DataSet dataSet = null;
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(cmdString, connString))
{
dataSet = new DataSet();
dataAdapter.Fill(dataSet);
}

return dataSet;
}

No comments:

Post a Comment