I am writing a C# executable and need to check if a given password for a Microsoft Access database is correct. It needs to be able to do this for both .mdb files and .accdb files. For .mdb I am using JET OLED and it works fine, but JET OLEDB doesn't support the newer versions of Microsoft Access so I use ACE OLEDB, but I get an error every time. Here is the relevant method:
public int CheckPassword(string password, string filePath)
{
// Ensure the correct provider for with .mdb(default) or .accdb
string providerName = "Microsoft.Jet.OLEDB.4.0";
if (Path.GetExtension(filePath) == ".accdb")
{
Console.WriteLine("Changed provider to ACE");
providerName = "Microsoft.ACE.OLEDB.12.0";
}
// Establish access to the file
var accessBuilder = new OleDbConnectionStringBuilder
{
Provider = providerName,
DataSource = filePath
};
accessBuilder["Jet OLEDB:Database Password"] = password;
// Attempt to enter a password and catch if it is incorrect
using (var conn = new OleDbConnection(accessBuilder.ConnectionString))
{
if (ConnectionState.Open != conn.State)
{
try
{
// If it fails here, likely due to an actual bad password.
conn.Open();
Console.WriteLine("0 - Success: Password Correct");
}
catch (OleDbException)
{
// Assumed bad password
Console.WriteLine("2 - Error: Password Incorrect");
return -1;
}
}
}
return 0;
}
When I give it an .accdb, the output is:
Changed provider to ACE
Unhandled Exception: System.Data.OleDb.OleDbException: Cannot open database
''. It may not be a database that your application recognizes, or the file
may be corrupt`.
When I give it an .mdb, the output is:
0 - Success: Password Correct
I've tried using a brand new Access file, but it still gives the same error