我正在编写一个 C# 可执行文件,需要检查 Microsoft Access 数据库的给定密码是否正确。它需要能够对 .mdb 文件和 .accdb 文件执行此操作。对于 .mdb,我使用的是 JET OLED,它工作正常,但 JET OLEDB 不支持较新版本的 Microsoft Access,所以我使用 ACE OLEDB,但每次都会出错。以下是相关方法:
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;
}
当我给它一个.accdb时,输出是:
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`.
当我给它一个 .mdb 时,输出是:
0 - Success: Password Correct
我尝试使用全新的 Access 文件,但它仍然给出相同的错误