【发布时间】:2015-05-19 16:58:07
【问题描述】:
我正在开发一个程序,该程序将为离开我们网络的用户自动执行分离过程。它执行的任务之一是将用户帐户从它所在的 OU 移动到 Former Employees OU。尽管我在使用DirectoryServices 执行其他进程时没有任何问题,但我在这一步中一直遇到问题。到目前为止,这是我的代码(注意:我知道我需要停止捕获和吃掉所有异常。这将在发布之前得到解决和纠正。关于我应该捕获哪些异常以及我不应该感谢的任何建议):
private const string AD_DOMAIN_NAME = "domain.com";
private const string AD_NEW_PASSWORD = "TestPassword123";
private const string AD_FORMER_EMPLOYEES_OU = "LDAP://OU=Former Employees,DC=domain,DC=com";
static DirectoryEntry CreateDirectoryEntry(string connectionPath,
string adUserName, string adPassword)
{
DirectoryEntry ldapConnection = null;
try
{
ldapConnection = new DirectoryEntry(AD_DOMAIN_NAME, adUserName, adPassword);
ldapConnection.Path = connectionPath;
ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
}
catch (Exception ex)
{
MessageBox.Show("Exception Caught in createDirectoryEntry():\n\n" + ex.ToString());
}
return ldapConnection;
}
private void btnProcessSeparation_Click(object sender, EventArgs e)
{
if (cboOffice.SelectedItem != null && lstUsers.SelectedItem != null)
{
string userOU = cboOffice.SelectedItem.ToString();
string userName = lstUsers.SelectedItem.ToString();
string userDn = "LDAP://OU=" + userOU + ",OU=Employees,DC=domain,DC=com";
using (DirectoryEntry ldapConnection = CreateDirectoryEntry(userDn))
{
using (DirectorySearcher searcher = CreateDirectorySearcher(ldapConnection,
SearchScope.OneLevel, "(samaccountname=" + userName + ")", "samaccountname"))
{
SearchResult result = searcher.FindOne();
if (result != null)
{
using (DirectoryEntry userEntry = result.GetDirectoryEntry())
{
if (userEntry != null)
{
using (DirectoryEntry formerEmployees = CreateDirectoryEntry(
AD_FORMER_EMPLOYEES_OU))
{
userEntry.MoveTo(formerEmployees); // This line throws an DirectoryServicesCOMException.
}
userEntry.CommitChanges();
userEntry.Close();
MessageBox.Show("Separation for {0} has completed successfully.", userName);
}
}
}
}
}
}
else
{
MessageBox.Show("Error, you did not select an OU or a user. Please try again.");
}
}
上面的代码在userEntry.MoveTo(formerEmployees); 行之前运行良好。该行抛出一个DirectoryServicesCOMException 和附加信息An invalid dn syntax has been specified. 这很奇怪,因为我使用的格式与其他DirectoryEntry 的格式相同,效果很好。我添加了一个断点并确认formerEmployees 设置为:LDAP://OU=Former Employees,DC=domain,DC=com。我直接从 Active Directory 中 OU 的 distinguishedName 属性复制了 LDAP:// 之后的所有内容,以确保它是正确的。
OU 名称中的空格是否会导致问题?我让它工作得很好,然后继续执行其他任务,并且一定是改变了一些破坏这个的东西。我一直在查看我认为的代码太多,但似乎无法理解为什么它认为我正在发送无效的 dn。
感谢您的帮助!
【问题讨论】:
-
"OU 名称中的空格是否导致问题?"创建一个没有空格的新 OU 并对其进行测试。要检查的另一件事是您是否对前员工的 OU 具有写入权限。最后,尝试阅读
AD_FORMER_EMPLOYEES_OU,看看是DN格式问题还是其他问题。 -
@David 感谢您的建议。原来是权限问题。我添加了一个重载的
CreateDirectoryEntry方法,它使用用户名和密码(这是我在上面的代码中输入的)。但是,如果您在上面的代码中注意到,我调用了只采用连接路径的方法。嗬!感谢您为我指明正确的方向!
标签: c# active-directory directoryservices