Voici le code que j'utilise, glané quelque part sur le net, et adapté pour mes besoins :
/// <summary>
/// MBD compact method (c) 2004 Alexander Youmashev
/// !!IMPORTANT!!
/// !make sure there's no open connections
/// to your db before calling this method!
/// !!IMPORTANT!!
/// </summary>
/// connection string to your db
/// FULL name
/// of an MDB file you want to compress.
private void CompactAccessDB(string connectionString, string mdwfilename) {
object[] oParams;
try {
//first check if a ldb file is not existing (opened connection to the db).
if (File.Exists(Path.Combine(_sAssemblyDir,"ArcDataArchiver.ldb"))) return;
// make a copy of the database before compacting it.
File.Copy(Path.Combine(_sAssemblyDir,"ArcDataArchiver.mdb"),Path.Combine(_sAssemblyDir,"ArcDataArchiver.mdb.sav"), true);
//create an inctance of a Jet Replication Object
object objJRO =
Activator.CreateInstance(Type.GetTypeFromProgID("JRO.JetEngine"));
//filling Parameters array
//cnahge "Jet OLEDB:Engine Type=5" to an appropriate value
// or leave it as is if you db is JET4X format (access 2000,2002)
//(yes, jetengine5 is for JET4X, no misprint here)
oParams = new object[] {
connectionString,
"Provider=Microsoft.Jet.OLEDB.4.0;Data" +
" Source=" + Path.Combine(_sAssemblyDir,"tempdb.mdb") + ";Jet OLEDB:Engine Type=5"};
//invoke a CompactDatabase method of a JRO object
//pass Parameters array
objJRO.GetType().InvokeMember("CompactDatabase",
System.Reflection.BindingFlags.InvokeMethod,
null,
objJRO,
oParams);
//database is compacted now
//to a new file C:\\tempdb.mdw
//let's copy it over an old one and delete it
File.Delete(mdwfilename);
File.Move(Path.Combine(_sAssemblyDir,"tempdb.mdb"), mdwfilename);
//clean up (just in case)
System.Runtime.InteropServices.Marshal.ReleaseComObject(objJRO);
objJRO=null;
}
catch (Exception e) {
Trace.WriteLine("ERROR in CompactAccessDB : " + e.Message + " / " + e.Source);
}
}
David.