Click here to Skip to main content
Click here to Skip to main content

Compact and Repair Access Database using C# and late binding

By , 20 Jul 2004
 

Introduction

This code compacts and repairs an MS Access database from a C# .NET application, no matter if it's a simple ".mdb", or a ".mdw"-secured workgroup-shared DB. It performs exactly the same operation as "Tools - Database Utils - Compact and Repair Database..." menu item in the MS Access application. The code uses "late binding" (creating COM-objects in memory at runtime), and that's why you don't need any annoying interop COM references in your project. You don't even need MS Office installed. Just make sure you have a Jet Engine (Jet is included in MDAC package, which comes with any Windows installation starting from NT 4).

Background

Don't you hate COM-library references in .NET-projects? I believe that pure .NET-code has to be free of any interops, RCWs, and other referenced COM-stuff. Basically because there's a load of different versions of MS libraries (for example, MS Office Object Library 9, 10, 11 etc.). We never know what version of MS Office is installed on a client machine, that's why we should access a COM-object via ProgID, and not CLSID. For example: you want to be sure, that when you call for an "Excel.Application", you get Excel, no matter what version of MS Office is installed. And when you add a reference "MS Excel 10 Object library", you add a strong limitation to your software! So... use System.Reflection and late binding.

Using the code

Just call a method CompactAccessDB. This method compacts and repairs your database.

Parameters:

  • connectionString - connection string to your database.
  • mdwfilename - is a full name (path+name) of an MDB-file you want to compact and repair.

Due to Jet limitations, the method compacts your database to a new file, so we have to copy the new compacted file over an old one.

When you call this method, make sure that there's no open connections to your database. Stop your threads.

Now, to the code:

/// <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>
/// <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 mdwfilename)
{
    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,
        "Provider=Microsoft.Jet.OLEDB.4.0;Data" + 
        " Source=C:\\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

    System.IO.File.Delete(mdwfilename);
    System.IO.File.Move("C:\\tempdb.mdb", mdwfilename);

    //clean up (just in case)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(objJRO);
    objJRO=null;
}

Points of Interest

Interesting, that Jet Engine 5 is used for JET4X databases. Be careful. See the table:

Jet OLEDB:Engine Type Jet x.x Format MDB Files
1 JET10
2 JET11
3 JET2X
4 JET3X
5 JET4X

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Alexander Yumashev
Founder Jitbit
United Kingdom United Kingdom
Member
I'm CEO/Founder and lead developer at Jitbit Software
 
Visit my blog at http://blog.jitbit.com/

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5 PinmemberStewBob18 Jul '12 - 5:17 
QuestionError when I run this Code PinmemberPooja N Khanapurkar20 Mar '12 - 4:41 
QuestionCompact and Repair Pinmemberlkn_o20 Mar '12 - 2:43 
GeneralMy vote of 5 Pinmemberkozura18 Feb '11 - 0:37 
GeneralCreate,Compact/Compress and Convert MDB database using ASP/VBScript Pingroupelizas11 Feb '10 - 23:21 
GeneralCreate,Compact/Compress and Convert MDB database using ASP/VBScript Pingroupelizas3 Feb '10 - 1:04 
GeneralReally useful PinmemberAlexander Stankov20 Sep '09 - 22:57 
Really useful code. Thanks. Keep up the good work.
QuestionCan it run on Windows 7? Pinmembertiendungdl13 Sep '09 - 18:29 
AnswerRe: Can it run on Windows 7? PinmemberJohn Reiter11 Oct '12 - 15:02 
QuestionInstance of type object ? PinmemberStuard25 Aug '09 - 15:12 
GeneralIt's Not Compacting or repairing MS access database properly.. Pinmembervermaraj8311 Aug '09 - 0:00 
GeneralEach iteration increases the size of my Access 97 MDB PinmemberMerrimackBobNH27 Jun '09 - 8:23 
GeneralြGreat PinmemberAung Sithu Kyaw2 Apr '08 - 16:02 
QuestionException has been thrown by the target of an invocation. PinmemberMember 26460376 Mar '08 - 22:11 
GeneralVery helpful. Thx. PinmemberMuaddubby27 Nov '07 - 17:57 
Generalthanks [modified] PinmemberM.S. Babaei16 Nov '07 - 23:24 
GeneralWarning PinmemberTom McAnnally15 Apr '07 - 14:04 
Questionhow can i deal with microsoft office by using c#? Pinmembergardinea20 Aug '06 - 22:52 
QuestionHow to set the connection.OpenSchema parameter ? Pinmemberliuzhuangli6 Jul '06 - 8:06 
Generalhelp - exception Pinmembersgrass-11125 Jun '06 - 10:03 
GeneralWhy not just this... PinmemberCabbi16 Jun '06 - 2:37 
GeneralRe: Why not just this... PinmemberLars [Large] Werner20 Jan '09 - 2:08 
Questionthe password has gone, why? Pinmemberjoeblack19 Dec '05 - 4:20 
AnswerRe: the password has gone, why? Pinmemberbolzmaster21 Dec '05 - 1:48 
AnswerRe: the password has gone, why? Pinmemberbolzmaster18 Jan '06 - 23:38 
QuestionIs this code absolutely safe ? PinsussAnonymous22 Sep '05 - 8:55 
QuestionCan I compact a local Access DB on remote PC? PinsussAnonymous9 Sep '05 - 21:54 
QuestionI need this code in C++ PinmemberM_Jafari26 Aug '05 - 3:01 
AnswerRe: I need this code in C++ Pinmemberhoang thoa18 May '06 - 23:03 
GeneralCom Object not registered PinmemberProgrammierhans21 Mar '05 - 3:17 
GeneralException PinsussBen1234567891 Mar '05 - 11:39 
GeneralRe: Exception PinmemberProgrammierhans18 Mar '05 - 5:36 
GeneralModified VB.NET Version Pinmemberjohndauphine16 Feb '05 - 11:53 
GeneralRe: Modified VB.NET Version Pinmembersuds458 Jun '08 - 5:28 
GeneralThanks PinsussAnonymous31 Jan '05 - 8:37 
GeneralBit Confussed PinsussAnonymous28 Jan '05 - 4:40 
Generalsmall issue Pinmemberwesman24 Dec '04 - 9:49 
GeneralRe: small issue Pinmemberwesman25 Dec '04 - 11:49 
GeneralInteropServices PinmemberMich2626 Sep '04 - 13:02 
GeneralThank you for the code exmple PinmemberMagnus Hauge19 Aug '04 - 9:54 
GeneralProgram Exception PinmemberMichael Greene4 Aug '04 - 11:13 
GeneralRe: Program Exception PinmemberAlexander Youmashev5 Aug '04 - 22:03 
GeneralRe: Program Exception PinmemberMike Gardiner16 Aug '05 - 4:48 
GeneralRe: Program Exception Pinmemberphamtoanthang19 Sep '07 - 17:57 
GeneralThanks PinmemberDavid ARNOLD30 Jul '04 - 0:13 
GeneralGreat PinsussDubant29 Jul '04 - 4:47 
GeneralProgress Callback Pinmemberbigals22 Jul '04 - 12:48 
GeneralExcellent piece of work PinmemberRussq21 Jul '04 - 22:10 
GeneralJust what I was looking for! Pinmemberbigals21 Jul '04 - 12:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 21 Jul 2004
Article Copyright 2004 by Alexander Yumashev
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid