开发者

how to compact Msaccess database using c#

is it possible to compact the Msaccess database usin开发者_如何学Pythong c# if so let me know the way?


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


...
//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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜