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

后端 未结 2 1956
天命终不由人
天命终不由人 2021-01-06 12:34

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

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-06 12:41

    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();
                    }
                }
            }
        }
    }
    

提交回复
热议问题