What is the best way to access Microsoft Access Database
object's Properties (like in CurrentDb.Properties
) from C# in Visual Studio 2010?
(Not essential: In fact I want to get rid of Replication in a few dozen databases "on demand". Replication is not in use for a few years, and it was OK for MS Access prior to 2013. Access 2013 rejects databases with this feature.)
You can iterate over and modify the properties in the Access database by using the Access DAO object library.
The following code iterates over the properties in the database as well over the different containers and its properties as well over the Documents and its properties in the Databases container. The output is written to the Debug Output window.
After that I pick a Property
from different property collections and change it's value. Do note that using the indexer on the collection will throw an exception if the property doesn't exist.
Make sure you have a reference to the Primary Interop Assembly for Microsoft Office 12.0 Access database engine Object Library (your version migth vary) so that you can have the following in your using statements:
using Microsoft.Office.Interop.Access.Dao;
Your method would go like this:
// Open a database
var dbe = new DBEngine();
var db = dbe.OpenDatabase(@"C:\full\path\to\your\db\scratch.accdb");
// Show database properties
DumpProperties(db.Properties);
// show all containers
foreach (Container c in db.Containers)
{
Debug.WriteLine("{0}:{1}", c.Name, c.Owner);
DumpProperties(c.Properties);
}
//Show documents and properties for a specific container
foreach (Document d in db.Containers["Databases"].Documents)
{
Debug.WriteLine("--------- " + d.Name);
DumpProperties(d.Properties);
}
// set a property on the Database
Property prop = db.
Properties["NavPane Width"];
prop.Value = 300;
// set a property on the UserDefined document
Property userdefProp = db
.Containers["Databases"]
.Documents["UserDefined"]
.Properties["ReplicateProject"];
userdefProp.Value = true;
Property dumper helper
private static void DumpProperties(Properties props)
{
foreach (Property p in props)
{
object val = null;
try
{
val = (object)p.Value;
}
catch (Exception e)
{
val = e.Message;
}
Debug.WriteLine(
"{0} ({2}) = {1}",
p.Name,
val,
(DataTypeEnum) p.Type);
}
}
I used this to overcome an exception being thrown on dynamic types (as the Value property turns out to be)