Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using OleDbConnection to Read Tab-Separated File

My tab-delimited file is something like this:

ISO ISO3    ISO-Numeric
AD  AND 20

I've been trying the following code with no luck.

OleDbConnection cn = new  OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= |DataDirectory|;Extended Properties='text;HDR=Yes;FMT=TabDelimited'");
OleDbCommand cmd = new OleDbCommand(@"SELECT * FROM countryInfo.txt", cn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);

cn.Open();

DataTable dt = new DataTable();
da.Fill(dt);

Here's a screenshot of the Dataset Visualizer. Its obviously not the output i'm after. alt text

Any suggestions? Here's my Schema.ini file. Its in the same directory as the text file.

[countryInfo.txt]
Format=TabDelimited
ColNameHeader=True
CharacterSet=ANSI

Should i just use something like FileHelpers instead?


@Hans Passant Here's a screenshot. alt text

like image 825
Prabath Yapa Avatar asked Oct 26 '22 03:10

Prabath Yapa


1 Answers

Create and save an schema.ini file into the application folder containing the following text:

------------------Schema.ini file starts here-----------------
[Data.txt]
ColNameHeader=True
Format=TabDelimited
Col1=First_Name Text
Col2=Middle_Initial Text
Col3=Last_Name Text
------------------Schema.ini file ends here-----------------

Then use the following code to load the Data.txt file:

string fileName = string.Format("{0}", AppDomain.CurrentDomain.BaseDirectory);   
string connectionString = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; " + "Extended Properties=\"text;HDR=YES;FMT=TabDelimited;\"", fileName);
string sql = "select * from " + "Data.txt";

OleDbConnection con = new OleDbConnection(connectionString);
con.Open();

OleDbDataAdapter dap = new OleDbDataAdapter(sql, con);
DataTable dt = new DataTable();
dt.TableName = "Data";
dap.Fill(dt);

con.Close();
like image 154
Uzair Tahir Avatar answered Nov 15 '22 07:11

Uzair Tahir