使用IDataReader在C#中读取dbf文件

时间:2011-07-08 05:54:03

标签: .net oledb datareader dbf

我正在尝试使用OleDb读取带有datareader的.dbf文件,如下所示:

const string OleDbConnectionString =
    @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydbase;Extended Properties=dBASE IV;";
    var connection = new OleDbConnection(OleDbConnectionString);
    connection.Open();

    var command = new OleDbCommand("select * from my.dbf", connection);

    reader = command.ExecuteReader();
    Console.WriteLine(reader.Read()); // true
    Console.WriteLine(reader[0].ToString()); // exception

例外属于InvalidCastException类型,并说:无法从System.__ComObject升级到IRowset。 当我尝试使用OleDbAdapter填表时,一切正常 如何使用IDataReader读取.dbf文件?

2 个答案:

答案 0 :(得分:1)

我认为您的路径可能有问题,因为您在connectionstring中有“C:\ mybase”,然后添加“my.dbf”,它加起来为“C:\ mybasemy.dbf”。

我提供代码如何使用数据集而不是阅读器打开和读取dbf。

string oledbConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\spcs\;Extended Properties=dBASE IV;User ID=Admin;Password=";

        OleDbConnection oledbConnection = new OleDbConnection(oledbConnectionString);

        string oledbQuery = @"SELECT * FROM KUND";

        try
        {
            OleDbCommand oledbCommand = new OleDbCommand(oledbQuery, oledbConnection);

            OleDbDataAdapter oledbAdapter = new OleDbDataAdapter(oledbCommand);

            DataSet oledbDataset = new DataSet();

            oledbAdapter.FillSchema(oledbDataset, SchemaType.Mapped);

            oledbConnection.Open();

            oledbAdapter.Fill(oledbDataset);

            foreach (DataRow row in oledbDataset.Tables[0].Rows)
            {
                System.Diagnostics.Trace.WriteLine(row[0].ToString());
            }
        }
        catch (Exception ex)
        {
            // Do something with ex
        }

答案 1 :(得分:0)

好的,尝试使用GetString:

const string OleDbConnectionString =
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydbase;Extended Properties=dBASE IV;";
OleDbConnection connection = new OleDbConnection(OleDbConnectionString);
connection.Open();

OleDbCommand command = new OleDbCommand("select * from my.dbf", connection);

OleDbDataReader reader = command.ExecuteReader();
Console.WriteLine(reader.Read()); // true
Console.WriteLine("{0}", reader.GetString(0)); // exception