how to compact Msaccess database using c#

后端 未结 3 637
情话喂你
情话喂你 2021-01-15 12:44

is it possible to compact the Msaccess database using c# if so let me know the way?

相关标签:
3条回答
  • 2021-01-15 13:19

    i used the article at:
    Compact and Repair an Access Database Programmatically Using C#

    i modified it a bit to make it simpler to use:

    public static bool CompactAndRepairAccessDB(string source, string destination)
    {
        try
        {
            JetEngine engine = (JetEngine)HttpContext.Current.Server.CreateObject("JRO.JetEngine");
            engine.CompactDatabase(string.Format("Data Source={0};Provider=Microsoft.Jet.OLEDB.4.0;", source),
                string.Format("Data Source={0};Provider=Microsoft.Jet.OLEDB.4.0;", destination));
            File.Copy(destination, source, true);
            File.Delete(destination);
            return true;
        }
        catch
        {
            return false;
        }
    }
    

    dont forget:
    Right Click Reference in the Solution Explorer -> Add Reference -> COM -> search 'jet' -> Add 'Microsoft Jet and Replication Objects...'

    and also add:

    using System.IO;
    using JRO;
    
    0 讨论(0)
  • 2021-01-15 13:24

    You can try something like this

    public static void CompactAndRepair(string accessFile, Microsoft.Office.Interop.Access.Application app)
            {
                string tempFile = Path.Combine(Path.GetDirectoryName(accessFile),
                                  Path.GetRandomFileName() + Path.GetExtension(accessFile));
    
                app.CompactRepair(accessFile, tempFile, false);
                app.Visible = false;
    
                FileInfo temp = new FileInfo(tempFile);
                temp.CopyTo(accessFile, true);
                temp.Delete();
            }
    

    See also Use the CompactRepair method of the Application object to compact and repair the database

    0 讨论(0)
  • 2021-01-15 13:32
    ...
    //invoke a CompactDatabase method of a JRO object
    //pass Parameters array
    objJRO.GetType().InvokeMember("CompactDatabase",
        System.Reflection.BindingFlags.InvokeMethod,
        null,
        objJRO,
        oParams);
    ...
    

    See more details at http://www.codeproject.com/KB/database/mdbcompact_latebind.aspx

    0 讨论(0)
提交回复
热议问题