使用OleDbConnection读取制表符分隔文件

时间:2010-10-31 15:20:38

标签: c# .net oledb text-files

我的制表符分隔文件是这样的:

ISO ISO3    ISO-Numeric
AD  AND 20

我一直在尝试以下代码而没有运气。

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);

这是Dataset Visualizer的屏幕截图。它显然不是我追求的输出。 alt text

有什么建议吗?这是我的Schema.ini文件。它与文本文件位于同一目录中。

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

我应该使用类似FileHelpers的东西吗?


@Hans Passant这是一个截图。 alt text

2 个答案:

答案 0 :(得分:2)

创建schema.ini文件并将其保存到包含以下文本的应用程序文件夹中:

------------------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-----------------

然后使用以下代码加载Data.txt文件:

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();

答案 1 :(得分:1)

嗯,一个明显的候选者是这个空白区域实际上不是一个标签而是空格。尝试FMT = Delimited()。使用十六进制查看器来查看真正存在的内容。背景资料is here

并且this thread显示了为什么使用像Jet这样过去9年没有得到支持的大量代码是错误的。在答案中,将schema.ini中的第一行留空。