Search code examples
c#sqldbase

How to add column to .DBF file?


One of the issues I have is that, I don't think the table has a name... its just a .dbf file

So I've been trying this:

public void SQLAlter(string dbffile, string ColumnName )
{
   //dbffile is "C:\MAPS\WASHINGTON\TLG_ROADS_L.DBF"
   //ColumnName is "State"
   if (File.Exists(dbffile))
   {
        System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection();
        conn.ConnectionString = @"DSN=dBase Files";
        conn.Open();
        System.Data.Odbc.OdbcCommand comm = new System.Data.Odbc.OdbcCommand();
        comm.CommandText = "ALTER TABLE " + dbffile + " ADD COLUMN " + ColumnName + " VARCHAR(1024)";
        comm.ExecuteNonQuery();
    }
 }

The error is :

base {System.Data.Common.DbException} = {"ERROR [42S02] [Microsoft][ODBC dBASE Driver] Cannot find table or constraint."}


Solution

  • This is actually the correct syntax

    comm.CommandText = "ALTER TABLE " + dbffile + " ADD COLUMN " + ColumnName + " VARCHAR(1024)";
    

    However if your filename is longer than 8 characters it will not find it. Even though I tried it will an appropriate length file name, the "Operation [is] not supported on a table that contains data."

    Various Internet links seem to indicate that one has to create a new table, and copy all the fields over.