For reasons beyond my control, I have to deal with a new Access MDB file that is downloaded, decrypted, and unzipped every month by an automated process I wrote. Despite the
In case anyone has to do something similar, here's what I wound up doing:
using System.Data;
using System.Data.OleDb;
namespace FTPAutomation.Utilities
{
public class AccessUtilities
{
public static void StripPasswordFromMDB(string currentPassword, string mdbFilePath)
{
var accessBuilder = new OleDbConnectionStringBuilder
{
Provider = "Microsoft.Jet.OLEDB.4.0",
DataSource = mdbFilePath
};
using (var conn = new OleDbConnection(accessBuilder.ConnectionString))
{
try
{
conn.Open();
return;
}
catch
{
// Do nothing, just let it fall through to try with password and exclusive open.
}
}
accessBuilder["Jet OLEDB:Database Password"] = currentPassword;
accessBuilder["Mode"] = "Share Exclusive";
using (var conn = new OleDbConnection(accessBuilder.ConnectionString))
{
if (ConnectionState.Open != conn.State)
{
conn.Open(); // If it fails here, likely due to an actual bad password.
}
using (
var oleDbCommand =
new OleDbCommand(string.Format("ALTER DATABASE PASSWORD NULL [{0}]", currentPassword), conn))
{
oleDbCommand.ExecuteNonQuery();
}
}
}
}
}
The way to change the password programmatically is detailed here.
Essentially, one needs to do the following:
Execute an alter statement on the database setting it's password to NULL as so:
ALTER DATABASE PASSWORD [Your Password] NULL;
Dispose the connection
Sample code taken from the source:
Private Function CreateDBPassword(ByVal Password As String, _
ByVal Path As String) As Boolean
Dim objConn as ADODB.Connection
Dim strAlterPassword as String
On Error GoTo CreateDBPassword_Err
' Create the SQL string to initialize a database password.
strAlterPassword = "ALTER DATABASE PASSWORD [Your Password] NULL;"
' Open the unsecured database.
Set objConn = New ADODB.Connection
With objConn
.Mode = adModeShareExclusive
.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data " & _
"Source=[Your Path];"
' Execute the SQL statement to secure the database.
.Execute (strAlterPassword)
End With
' Clean up objects.
objConn.Close
Set objConn = Nothing
' Return true if successful.
CreateDBPassword = True
CreateDBPassword_Err:
Msgbox Err.Number & ":" & Err.Description
CreateDBPassword = False
End Function