我正在为我的公司创建一个应用程序,以将用户和组添加到 AD。
我可以很好地添加用户,但很难将用户添加到组中。
我得到以下信息:抛出异常:
'System.DirectoryServices.DirectoryServicesCOMException' in System.DirectoryServices.dll
请帮忙:-D
这是我用来将用户添加到组的代码片段。
AdAccountName
和 GroupStr
是先前代码中已填充的变量(未在下面显示)。
try
{
string admin_userName = "administrator";
string admin_password = "password";
string LDAP = "LDAP://192.168.231.128/CN=Users,DC=home,DC=lab";
DirectoryEntry dirEntry = new DirectoryEntry(LDAP + GroupStr, admin_userName, admin_password);
dirEntry.Invoke("add", new object[] {ADAccountNameStr});
dirEntry.CommitChanges();
dirEntry.Close();
}
catch (System.DirectoryServices.DirectoryServicesCOMException E)
{
//doSomething with E.Message.ToString();
}
最后,这是因为我没有为用户和组使用整个 LDAP 上下文。
对于用户和组,我插入了相关名称。
实际上需要像下面这样
用户名:
"CN=jdoe,CN=Users,DC=test,DC=com";
团体:
"LDAP://192.168.231.128/CN=IT,OU=Departments,DC=test,DC=com"
你可以像这样改进你的代码。
try
{
string admin_userName = "administrator";
string admin_password = "password";
string LDAP = "LDAP://192.168.231.128/CN=Users,DC=home,DC=lab";
using (DirectoryEntry dirEntry = new DirectoryEntry(LDAP, admin_userName, admin_password))
{
using (DirectoryEntry groupEntry = dirEntry.Children.Find(GroupStr))
{
groupEntry.Invoke("Add", new object[] { ADDAccountNameStr });
groupEntry.CommitChanges();
}
}
}
catch (System.DirectoryServices.DirectoryServicesCOMException ex)
{
// Log or handle the exception appropriately
Console.WriteLine("Error: " + ex.Message);
}