由于我无法控制的原因,我必须处理一个新的Access MDB文件,该文件每个月都会通过我编写的自动化过程下载,解密和解压缩。尽管有PGP加密,但发件人(保险公司)拒绝发送MDB非密码保护。
不幸的是,在文件下载之后,它被立即处理,并且假定没有密码,因此由于OleDbException显示我们的密码错误而没有处理这些文件。我们知道密码,并且我们知道连接字符串的“with database password”选项:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;
这只能解决部分问题,因为其他部门需要稍后访问这些文件,而且他们不知道密码。到目前为止,我只能通过在打开文件时按住Shift,在密码提示下取消,通过打开Access进程再次打开文件,同时再次按住Shift并单击“打开独占”,继续工作通过密码对话框保持Shift,然后通过安全工具取消设置密码。
我想要做的就是使用C#以编程方式在MDB文件下载后立即取消设置数据库密码。有没有办法做到这一点,或者我每次获得新文件时都必须亲自干预,完全违背自动化的目的?
答案 0 :(得分:5)
以编程方式更改密码的方法详见here。
基本上,需要做以下事情:
对数据库执行alter语句,将其密码设置为NULL,如下所示:
ALTER DATABASE PASSWORD [您的密码] NULL;
处理连接
从源代码中获取的示例代码:
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
答案 1 :(得分:3)
如果有人必须做类似的事情,这就是我最后做的事情:
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();
}
}
}
}
}