Search code examples
c#odbcdbf

C# DBF Error Opening


I am trying to write a program to read a DBF file and put it into a datatable. I don't have much experience working with FoxPro database. Below is the funcation that opens the dbf. I pass the filename into the function.

private DataTable loadFile(string FileName)
{
    System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection();
    conn.ConnectionString = "DRIVER={Microsoft dBase Driver (*.dbf)};Deleted=1";
        DataTable dt = new DataTable();
    try
    {
        conn.Open();
        System.Data.Odbc.OdbcCommand comm = new System.Data.Odbc.OdbcCommand();
        comm.CommandText = @"SELECT * FROM " + @FileName;

        comm.Connection = conn;

        dt.Load(comm.ExecuteReader());
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    finally{
        conn.Close();
    }
    return dt;

}

The Variable for the filename is

"C:\\Users\\psun\\Desktop\\New folder\\plog.DBF"

At run time I get this error

    ERROR [42000] [Microsoft][ODBC dBase Driver] Syntax error in FROM clause.
   at System.Data.Odbc.OdbcConnection.HandleError(OdbcHandle hrHandle, RetCode retcode)
   at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior behavior, String method, Boolean needReader, Object[] methodArguments, SQL_API odbcApiMethod)
   at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior behavior, String method, Boolean needReader)
   at System.Data.Odbc.OdbcCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Odbc.OdbcCommand.ExecuteReader()
   at UpLoad.Form1.loadExcel(String FileName) in c:\Users\psun\Documents\Visual Studio 2012\Projects\PLOGReader\PLOGReader\Form1.cs:line 60

Solution

  • First, if you are working with Foxpro tables, I would not use the dBase driver.

    Get the Microsoft Visual Foxpro OleDb Provider

    Second, look into connections strings. You DO NOT want the connection string to mention an actual table.dbf, but just the PATH to where the database files are located. Then, your queries are as simple as...

    select * from SomeTable

    Additionally, there are plenty of other Q&A associated with VFP and OleDB. If you do a seach specifically of my user ID plus those tags, you will get a list of the questions I've specifically offered out here. There are many from running scripts, simple querying, using parameterized queries, etc.

    Here is an example search you could put in... user:74195[vfp][oledb]