StuffHappens
StuffHappens

Reputation: 6557

Using IDataReader for reading dbf file in C#

I'm trying to read .dbf file with datareader using OleDb like this:

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

The exception is of InvalidCastException type and says: Unable to case from System.__ComObject to IRowset. When I tried to use OleDbAdapter to fill a table everything worked fine.
How do I read .dbf file using IDataReader?

Upvotes: 0

Views: 5632

Answers (2)

Andreas
Andreas

Reputation: 301

I think your path might be wrong since you have "C:\mybase" in the connectionstring and then add "my.dbf" which adds up to "C:\mybasemy.dbf".

Ill provide code how i open and read a dbf using a dataset instead of a reader.

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
        }

Upvotes: 1

kazinix
kazinix

Reputation: 30093

Okay, try using 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

Upvotes: 0

Related Questions