Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically remove a known password from an Access DB?

Tags:

c#

ms-access

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 PGP encryption, the sender (an insurance company) refuses to send the MDB non-password-protected.

Unfortunately, immediately after the file is downloaded, it's processed, and is assumed to have no password, so these files aren't being processed due to an OleDbException showing that we have the wrong password. We know the password, and we know about the "with database password" option for connection strings:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;

That only solves part of the problem, since another department needs to access the files later, and they don't know the password. So far, I've only been able to get it to work by holding Shift while I open the file, cancel at the password prompt, open the file again through an open Access process while holding Shift again and clicking "Open Exclusive", continuing to hold Shift while going through the password dialog, then unsetting the password through the security tools.

What I'd like to do is just programmatically unset the DB password on the MDB file as soon as it's downloaded, using C#. Is there a way to do that, or do I have to personally intervene every time we get a new file, completely defeating the purpose of automation?

like image 753
Chris Doggett Avatar asked Feb 24 '23 03:02

Chris Doggett


1 Answers

The way to change the password programmatically is detailed here.

Essentially, one needs to do the following:

  1. Open a connection to the database using ADO.NET
  2. Execute an alter statement on the database setting it's password to NULL as so:

    ALTER DATABASE PASSWORD [Your Password] NULL;

  3. 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
like image 192
Icarus Avatar answered Mar 29 '23 23:03

Icarus