无法使用ACE OLEDB访问Microsoft Access(.accdb)文件,但可以使用JET OLEDB访问(.mdb)文件

时间:2019-01-04 16:30:39

标签: c# sql oledb aceoledb

我正在编写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文件,但仍然会出现相同的错误

0 个答案:

没有答案