MS-Access / Getting Started

Creating the Target Database

The first thing you should do is create the file that you're going to build. This is so that you can modify it without changing the original. Start by creating the CreateTargetDatabase method. If you check the option to create an ACCDE or MDE file, call another method called CreateACCDEFile that will be defined in a moment.

private DAO.Database CreateTargetDatabase()
{
    // creates the destination database
    if (createACCDE.Checked)
    {
    CreateACCDEFile();
    }

If you're not creating an ACCDE or MDE file, you need to make a copy of the file to avoid overwriting the original:

    else
    {
    	try
    	{
		// copy the file
		File.Copy(inputDatabase.Text, outputDatabase.Text);
	}

If the copy fails, the .NET Framework will throw an IOException. The most common reason for this is that the file already exists. If we receive this exception, we'll delete the file first and then copy it again.

	catch (IOException)
	{
	    // delete the file first and then copy the file
	    File.Delete(outputDatabase.Text);
	    File.Copy(inputDatabase.Text, outputDatabase.Text);
	}
    }

At this point, the file should be created - be it an ACCDE or MDE file, or simply a copy of the original. Because the CreateTargetDatabase method returns a Database object in DAO, we need to open the database and return it to the caller.

    // return the new database (opened)
    try
    {
	return myEngine.OpenDatabase(
	    outputDatabase.Text,
	    false,
	    false,
	    string.Empty);
    }
    catch (COMException)
    {
	return null;
    }
}

To create an ACCDE or MDE file, we're going to cheat. The SysCmd function in Access defines a hidden command (603) to create an ACCDE or MDE file. To use this function, we need to use the Access object model, as shown in the following code:

private void CreateACCDEFile()
{
    // launch Access
    myApp = new ACC.ApplicationClass();
    // cannot create MDE files in disabled mode
    // set AutomationSecurity to Low
    myApp.AutomationSecurity =
	OFF.MsoAutomationSecurity.msoAutomationSecurityLow;
    // create an ACCDE/MDE
    ACC.AcSysCmdAction syscmd603 = (ACC.AcSysCmdAction)603;
    object rc = myApp.SysCmd(
	syscmd603,
	inputDatabase.Text,
	outputDatabase.Text);
    // close
    myApp.Quit(ACC.AcQuitOption.acQuitSaveNone);
    myApp = null;
}

The SysCmd 603 command is not documented by Microsoft. You should be aware that calling undocumented methods is not without risk. While this will work in Access 2007, there are no guarantees that it will be supported in future versions of Access.

[Previous] [Contents] [Next]