Click here to Skip to main content
6,595,854 members and growing! (18,137 online)
Email Password   helpLost your password?
Database » Database » General     Advanced

Compact and Repair Access Database using C# and late binding

By Alexander Yumashev

The code compacts and repairs an MS Access database from C# code using a JRO.JetEngine COM-object. Binding occurs at runtime, no references, no interops. Pure System.Reflection.
C#.NET 1.0, .NET 1.1, Win2K, WinXP, Win2003, COM, COM+, VS.NET2003, DBA, Dev
Posted:20 Jul 2004
Views:132,472
Bookmarked:74 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
46 votes for this article.
Popularity: 7.34 Rating: 4.42 out of 5
3 votes, 6.5%
1

2
1 vote, 2.2%
3
7 votes, 15.2%
4
35 votes, 76.1%
5

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


Member
Senior software developer in a financial services company, Moscow, Russia.

Developing C# asp.net applications, winforms applications, databases (SQL Server 2000/2005) etc. etc.
Occupation: Web Developer
Location: Russian Federation Russian Federation

Other popular Database articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 42 (Total in Forum: 42) (Refresh)FirstPrevNext
GeneralReally useful PinmemberAlexander Stankov23:57 20 Sep '09  
QuestionCan it run on Windows 7? Pinmembertiendungdl19:29 13 Sep '09  
GeneralInstance of type object ? PinmemberStuard16:12 25 Aug '09  
GeneralIt's Not Compacting or repairing MS access database properly.. Pinmembervermaraj831:00 11 Aug '09  
GeneralEach iteration increases the size of my Access 97 MDB PinmemberMerrimackBobNH9:23 27 Jun '09  
GeneralြGreat PinmemberAung Sithu Kyaw17:02 2 Apr '08  
QuestionException has been thrown by the target of an invocation. PinmemberMember 264603723:11 6 Mar '08  
GeneralVery helpful. Thx. PinmemberMuaddubby18:57 27 Nov '07  
Generalthanks [modified] PinmemberM.S. Babaei0:24 17 Nov '07  
GeneralWarning PinmemberTom McAnnally15:04 15 Apr '07  
Generalhow can i deal with microsoft office by using c#? Pinmembergardinea23:52 20 Aug '06  
GeneralHow to set the connection.OpenSchema parameter ? Pinmemberliuzhuangli9:06 6 Jul '06  
Generalhelp - exception Pinmembersgrass-11111:03 25 Jun '06  
GeneralWhy not just this... PinmemberCabbi3:37 16 Jun '06  
GeneralRe: Why not just this... PinmemberLars [Large] Werner3:08 20 Jan '09  
Generalthe password has gone, why? Pinmemberjoeblack5:20 19 Dec '05  
QuestionRe: the password has gone, why? Pinmemberbolzmaster2:48 21 Dec '05  
AnswerRe: the password has gone, why? Pinmemberbolzmaster0:38 19 Jan '06  
GeneralIs this code absolutely safe ? PinsussAnonymous9:55 22 Sep '05  
GeneralCan I compact a local Access DB on remote PC? PinsussAnonymous22:54 9 Sep '05  
QuestionI need this code in C++ PinmemberM_Jafari4:01 26 Aug '05  
AnswerRe: I need this code in C++ Pinmemberhoang thoa0:03 19 May '06  
GeneralCom Object not registered PinmemberProgrammierhans4:17 21 Mar '05  
GeneralException PinsussBen12345678912:39 1 Mar '05  
GeneralRe: Exception PinmemberProgrammierhans6:36 18 Mar '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 20 Jul 2004
Editor: Smitha Vijayan
Copyright 2004 by Alexander Yumashev
Everything else Copyright © CodeProject, 1999-2009
Web16 | Advertise on the Code Project