Access “Compact and Repair” programmatically

前端 未结 7 669
逝去的感伤
逝去的感伤 2020-12-03 22:28

Is it possible to \"compact and repair\" an Access database programmatically somehow (using ADOX, using OleDbConnection etc.)?

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 22:37

    This solution works with the Access 2010 Database Engine:

    Required reference:

    Microsoft.Office.interop.access.dao
    

    Code:

    public void CompactDb(
        string sourceFilePath, string destFilePath, string password)
    {
        var dbEngine = new Microsoft.Office.Interop.Access.Dao.DBEngine();
    
        dbEngine.CompactDatabase(sourceFilePath, destFilePath,
            ";pwd=" + password, null, ";pwd=" + password);
    }
    

    (The sourceFilePath and destFilePath should not be the same!)

    CompactDatabase method parameters (from reflection):

    void CompactDatabase(
        string SrcName, string DstName,
        object DstLocale = Type.Missing,
        object Options = Type.Missing,
        object SrcLocale = Type.Missing);
    

    Make sure you run it under the same platform as the AccessDatabaseEngine (or Office) you installed (x86/x64).

提交回复
热议问题