/*
   compact a database with Access
   taken from Example03.cs
*/
private void Example03Main()
{
   // start access 
   Access.Application accessApplication = new Access.Application();

   // create database name 
   string fileExtension = GetDefaultExtension(accessApplication);
   string documentFile = string.Format("{0}\\Example03{1}", 
Application.StartupPath,
fileExtension); // delete old database if exists if (System.IO.File.Exists(documentFile)) System.IO.File.Delete(documentFile); // create database DAO.Database newDatabase = accessApplication.DBEngine.Workspaces[0].CreateDatabase(
documentFile, LanguageConstants.dbLangGeneral); accessApplication.DBEngine.Workspaces[0].Close(); // setup database connection OleDbConnection oleConnection = new OleDbConnection(
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + documentFile); oleConnection.Open(); // create table OleDbCommand oleCreateCommand = new OleDbCommand(
"CREATE TABLE NetOfficeTable(Column1 Text, Column2 Text)", oleConnection); oleCreateCommand.ExecuteReader().Close(); // write some data with plain sql & close for (int i = 0; i < 20000; i++) { string insertCommand = string.Format(
"INSERT INTO NetOfficeTable(Column1, Column2) VALUES(\"{0}\", \"{1}\")",
i, DateTime.Now.ToShortTimeString()); OleDbCommand oleInsertCommand = new OleDbCommand(insertCommand, oleConnection); oleInsertCommand.ExecuteReader().Close(); } oleConnection.Close(); // now we do CompactDatabase string newDocumentFile = string.Format("{0}\\CompactDatabase{1}",
Environment.CurrentDirectory,
fileExtension); if (File.Exists(newDocumentFile)) File.Delete(newDocumentFile); accessApplication.DBEngine.CompactDatabase(documentFile, newDocumentFile); // close access and dispose reference accessApplication.Quit(AcQuitOption.acQuitSaveAll); accessApplication.Dispose(); FinishDialog fDialog = new FinishDialog("Database saved.", newDocumentFile); fDialog.ShowDialog(this); } /// <summary> /// returns the valid file extension for the instance. for example ".mdb" or ".accdb" /// </summary> /// <param name="application">the instance</param> /// <returns>the extension</returns> private static string GetDefaultExtension(Access.Application application) { // Access 2000 doesnt have the Version property(unfortunately) // we check for support with the EntityIsAvailable method, implemented by NetOffice if (!application.EntityIsAvailable("Version")) return ".mdb"; double Version = Convert.ToDouble(application.Version, CultureInfo.InvariantCulture); if (Version >= 12.00) return ".accdb"; else return ".mdb"; }

Last edited Jun 13, 2012 at 1:43 PM by SebastianDotNet, version 5