Previous Thread

7/26/2006 7:25:01 PM    Compact Database Works ... Most of the Time!
I've implemented code that I'm posted below that compacts an MDB database. 
 
It works every single time EXCEPT in the same session that the database was 
 
created (and populated).  Restart the app and populate some more and it works 
 
perfectly fine. 
 
Why would this be happening? 
 
Robert 
 
/// <summary> 
 
/// Created from here: 
 
http://www.codeproject.com/cs/database/mdbcompact_latebind.asp 
 
/// </summary> 
 
/// <param name="connectString"></param> 
 
/// <param name="fullFilename"></param> 
 
public static void CompactDatabase(string connectString, string 
 
fullFilename) 
 
{ 
 
try 
 
{ 
 
object[] oParams; 
 
// Create an instance of a Jet Replication Object 
 
object objJRO = 
 
Activator.CreateInstance(Type.GetTypeFromProgID("JRO.JetEngine")); 
 
string tempDBPath = SysInfo.Data.Paths.Temp + "TempDB.mdb"; 
 
if (File.Exists(tempDBPath)) 
 
File.Delete(tempDBPath); 
 
// Fill Parameters array 
 
// Note: change "Jet OLEDB:Engine Type=5" to an appropriate value 
 
//       or leave it as is if your DB is JET4X format (Access 
 
2000,2002) 
 
//       (yes, jetengine5 is for JET4X, no misprint here) 
 
oParams = new object[] { connectString, 
 
"Provider=Microsoft.Jet.OLEDB.4.0;Data" + 
 
" Source=" + tempDBPath + ";Jet 
 
OLEDB:Engine Type=5"}; 
 
// Invoke the CompactDatabase method of a JRO object 
 
// Pass Parameters array 
 
// Note for MSDN Group: This is where the error is occurring!!! 
 
objJRO.GetType().InvokeMember("CompactDatabase", 
 
System.Reflection.BindingFlags.InvokeMethod, 
 
null, 
 
objJRO, 
 
oParams); 
 
// Database is compacted now to a new file 
 
// Let's copy it over an old one and delete it 
 
System.IO.File.Delete(fullFilename); 
 
System.IO.File.Move(tempDBPath, fullFilename); 
 
// Clean up (just in case) 
 
System.Runtime.InteropServices.Marshal.ReleaseComObject(objJRO); 
 
objJRO = null; 
 
} 
 
catch (Exception ex) 
 
{ 
 
// An error is occuring everytime this method is called right after 
 
the MDB file is created & populated. 
 
// So until we can resolve it we'll call 'Debug.Fail' rather than 
 
'Tools.ShowMessage'. 
 
Debug.Fail("Compacting MDB database failed.\n\nError message: " + 
 
ex.Message, "DBTools.CompactDatabase"); 
 
} 
 
}