C# Test for Table in Access DB Through OleDb
This is up here because it was a pain to try and perform through SQL, I ended up looking at some really good articles for granting select permissions to the admin user until I found that user level permissions weren't a thing for .Accdb files... *sigh* so if you want to be able to test for the existence of a table in an access database through OleDb then here's your code:
public bool TableExists(string _TableName, string _ConnectionString = null)
{
bool tablefound = false;
using (DBConn = new OleDbConnection(CheckConnectionString(_ConnectionString)))
{
DBConn.Open();
var schema = DBConn.GetOleDBSchemaTable(OleDbSchemaGuid.Tables , new object[] { null, null, null, "TABLE"});
DBConn.Close();
if (schema.Rows
.OfType()
.Any(r => r.ItemArray[2].ToString().ToLower() == _TableName.ToLower()))
{
tablefound = true;
}
}
return tablefound;
}
if you are using an older file extension though then there's always the path that I tried to take initially as an option:
// This is the string you'll need to throw at the database to ensure you've got permissions for the below
string GrantPerms = "GRANT SELECT ON MSysObjects TO Admin;"
// This is the string you'll want for your sql select, it will return 0 or 1
string sql = @"SELECT iif(DlookUp(""Name"",""MSysObjects"",""Name = '{0}'"") is null, 0, 1) ";
string finalSql = String.Format(sql, _TableName);
