Programmatically Compact and Repair Access Example

string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
                            Data Source=" + mainPath + @";
                            Jet OLEDB:Engine Type=5;
                            Jet OLEDB:Database Password=XXX;"
string compactedNewFilePathAndName = mainPath.Replace(".accdb", "_TEMP.accdb");
CompactAndRepair.CompactAccessDB(connectionString, compactedNewFilePathAndName, mainPath);


class CompactAndRepair
/// <summary>
/// MBD compact method (c) 2004 Alexander Youmashev
/// !make sure there's no open connections
/// to your db before calling this method!
/// </summary>
/// <param name="connectionString">connection string to your db</param>
/// <param name="mdwfilename">FULL name
/// of an MDB file you want to compress.</param>

public static void CompactAccessDB(string connectionString,
              string compactedNewFilePathAndName, string mainPath)
   object[] oParams;
   //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,
                  Data Source=" + compactedNewFilePathAndName + @";
                  Jet OLEDB:Database Password=XXXX;
                  Jet OLEDB:Engine Type=5"

    oParams = new object[] { connectionString,
            connectionString.Replace(mainPath, compactedNewFilePathAndName)
   //invoke a CompactDatabase method of a JRO object
   //pass Parameters array
                              null, objJRO, oParams);
   catch (Exception ex)
      //do something


   //clean up (just in case)
   objJRO = null;

   //database is compacted now
   //to a new file compactedNewFilePathAndName
   //let's copy it over an old one and delete it
      System.IO.File.Move(compactedNewFilePathAndName, mainPath);
   }    catch (Exception ex){}


Popular posts from this blog

c# Service Play Sound with NAudio example by Moshe

SOLVED The item could not be indexed successfully because the item failed in the indexing subsystem

JS/JQ simulate Enter event