阅读固定格式文本文件 - 第2部分

时间:2012-01-30 13:25:04

标签: c# c#-4.0 oledb

这是question:

的后续问题

我正在尝试使用Microsoft.ACE.OLEDB.12.0提供程序读取固定格式文本文件。我有六种不同的方法来设置驱动程序和/或提供程序,并且每次都遇到同样的问题。我出于某种原因甚至无法“开始”因为“无法找到可安装的ISAM”异常或驱动程序的错误和异常。

系统安装了Office 2007,因此“无法找到可安装的ISAM”没有多大意义。

有没有人看到以下代码的问题?

string DATABASE_PROVIDER = "Provider=Microsoft.ACE.OLEDB.12.0";
string CVS = Application.StartupPath + @"\Data.txt";
string connectionString = DATABASE_PROVIDER = ";Data Source=" + CVS +";Extended Properties=text;HDR=Yes;FMT=Fixed";
string field ="*";
string table ="Data";
string StringQueryCMD = "SELECT" + field+" FROM " + table;
OleDbConnection myConnection = new OleDbConnection( connectionString );
OleDbCommand cmd = myConnection.CreateCommand();
cmd.CommandText = StringQueryCmd;
myConnection.Open(); // <---- "Could not find installable ISAM" exception here
OleDataAdapter myDataAdapter = new OleDbDataAdapter(cmd);
DataTable Table = new DataTable("Data");// <---- "Could not find installable ISAM" exception here

myDataAdapter.Fill(Table);

2 个答案:

答案 0 :(得分:2)

我会使用FileHelpers库来读取固定长度文件,而不是ADO.Net。

<强>更新 在那种情况下,我你需要一个ini文件和txt文件一起定义txt文件。列宽,名称等

另一种选择是完全放弃ado.net并创建一个简单的固定长度文件阅读器。

var file = new FileInfo("path");
using(var reader = file.Open())
while(reader.Read())
{
   //parse the line
   yield return the object representing the parsed line.
}

答案 1 :(得分:0)

我最终采用了略微不同的解决方案。 “无法找到可安装的ISAM”例外的解决方案是使用以下内容:

string EXTENDED_PROPERTIES = @"Extended Properties=""Text;HDR=YES;FMT=FixedLength;""";

解决方案的关键是围绕“扩展属性”值的(s)。我能够使用文件内容填充DataTable,我认为存在问题ini文件,因此它包含对我来说无用的字符串“-----”。

所以我最终只是阅读了访问数据库。

string DATABASE_PROVIDER = "Provider=Microsoft.ACE.OLEDB.12.0";
string CVS Application.StartupPath + ""\\Database.accdb";
string DATA_SOURCE = "Data Source" + CVS;
string connectionString = DATABASE_PROVIDER + DATA_SOURCE;
string TABLE = " FROM STUFF";
string SELECT = "SELECT CODE, NAME, ICON, FUNCTION;
string StringQueryCmd = SELECT + TABLE;

OleDbConnection MyConnection = new OleDbConnection(connectionString);
OleDbCommand Command = OleDbCommand(StringQueryCmd,MyConnection);
OleDbAdapter MyDataAdapter = new OleDbAdapter(Command);
DataSet MyDataSet = new DataSet();
DataTable MyDataTable = new DataTable();
MyConnection.Open();
MyDataAdapter.Fill(MyDataSet,"STUFF");
MyConnection.Close();

一旦你有了DataTable,你理论上可以使用LINQ to DataSet而不是处理DataTable。