C# Read from .DBF files into a datatable

TheCoder picture TheCoder · Mar 12, 2014 · Viewed 40.4k times · Source

I need to connect to a .dbf file in visual Studio using C# and populate a data table. Any ideas? I can currently view the tables in Visual Fox Pro 9.0

Code I have tried and failed, keep getting

External table is not in the expected format.

private OleDbConnection conn;
private OleDbCommand cmd;
private OleDbDataReader dr;
private string sqlStr = "";
private DataSet myDataSet;
private OleDbDataAdapter myAdapter;


void test2()
{
    conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\PC1\Documents\\Visual FoxPro Projects\\;Extended Properties=DBASE IV;");
    conn.Open();
    sqlStr = "Select * from Clients.dbf";
    //Make a DataSet object
    myDataSet = new DataSet();
    //Using the OleDbDataAdapter execute the query
    myAdapter = new OleDbDataAdapter(sqlStr, conn);
    //Build the Update and Delete SQL Statements
    OleDbCommandBuilder myBuilder = new OleDbCommandBuilder(myAdapter);         

    //Fill the DataSet with the Table 'bookstock'
    myAdapter.Fill(myDataSet, "somename");
    // Get  a FileStream object
    FileStream myFs = new FileStream
          ("myXmlData.xml", FileMode.OpenOrCreate, FileAccess.Write);
    // Use the WriteXml method of DataSet object to write XML file from the   DataSet
    //  myDs.WriteXml(myFs);
    myFs.Close();
    conn.Close();
}

Answer

TheCoder picture TheCoder · Mar 21, 2014

This code worked for me!

public DataTable GetYourData()
    {
        DataTable YourResultSet = new DataTable();

        OleDbConnection yourConnectionHandler = new OleDbConnection(
            @"Provider=VFPOLEDB.1;Data Source=C:\Users\PC1\Documents\Visual FoxPro Projects\");

        // if including the full dbc (database container) reference, just tack that on
        //      OleDbConnection yourConnectionHandler = new OleDbConnection(
        //          "Provider=VFPOLEDB.1;Data Source=C:\\SomePath\\NameOfYour.dbc;" );


        // Open the connection, and if open successfully, you can try to query it
        yourConnectionHandler.Open();

        if (yourConnectionHandler.State == ConnectionState.Open)
        {
            string mySQL = "select * from CLIENTS";  // dbf table name

            OleDbCommand MyQuery = new OleDbCommand(mySQL, yourConnectionHandler);
            OleDbDataAdapter DA = new OleDbDataAdapter(MyQuery);

            DA.Fill(YourResultSet);

            yourConnectionHandler.Close();
        }

        return YourResultSet;
    }