Here is my solution to relinking DAO tables using C#.
My application uses a central MS Access database and 8 actual databases that are linked in.
The central database is stored locally to my C# app but the application allows for the 8 data databases to be located elsewhere. On startup, my C# app relinks DAO tables in the central database based on app.config settings.
Aside note, this database structure is the result of my app originally being a MS Access App which I ported to VB6. I am currently converting my app to C#. I could have moved off MS Access in VB6 or C# but it is a very easy to use desktop DB solution.
In the central database, I created a table called linkedtables with three columns TableName, LinkedTableName and DatabaseName.
On App start, I call this routine
Common.RelinkDAOTables(Properties.Settings.Default.DRC_Data
, Properties.Settings.Default.DRC_LinkedTables
, "SELECT * FROM LinkedTables");
Default.DRC_Data - Current folder of central access DB
Default.DRC_LinkedTables - Current folder of 8 data databases
Here is code does the actual relinking of the DAO Tables in C#
public static void RelinkDAOTables(string MDBfile, string filepath, string sql)
{
DataTable linkedTables = TableFromMDB(MDBfile, sql);
dao.DBEngine DBE = new dao.DBEngine();
dao.Database DB = DBE.OpenDatabase(MDBfile, false, false, "");
foreach (DataRow row in linkedTables.Rows)
{
dao.TableDef table = DB.TableDefs[row["Name"].ToString()];
table.Connect = string.Format(";DATABASE={0}{1} ;TABLE={2}", filepath, row["database"], row["LinkedName"]);
table.RefreshLink();
}
}
Additional code written to fetch data from a access database and return it as a DataTable
public static DataTable TableFromOleDB(string Connectstring, string Sql)
{
try
{
OleDbConnection conn = new OleDbConnection(Connectstring);
conn.Open();
OleDbCommand cmd = new OleDbCommand(Sql, conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
catch (OleDbException)
{
return null;
}
}
public static DataTable TableFromMDB(string MDBfile, string Sql)
{
return TableFromOleDB(string.Format(sConnectionString, MDBfile), Sql);
}