似乎无法通过 Windows 表单中的复选框将用户添加到 AD 安全组



我的windows窗体无法正常运行。我不知道我哪里出错了,因为许多其他来源都说要以这种方式向组添加用户。

System.Runtime.InteropServices。COMException: 'Unspecified error'

在这一行失败:de.Properties["member"].Add(up);

但是我不明白为什么它失败了。我也尝试过使用string group = chklbADGroups.CheckedItems,但无济于事,这就是为什么我尝试指定组名的原因。

foreach (string item in chklbADGroups.Items)
{
string group = "CN=mygroup";
bool isChecked = chklbADGroups.GetItemChecked(chklbADGroups.FindStringExact(item));
string LDAP = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
PrincipalContext ouContext = new PrincipalContext(ContextType.Domain, LDAP);
WindowsIdentity.GetCurrent();
SearchResult results;
DirectorySearcher ds = null;
DirectoryEntry de = new
DirectoryEntry(ouContext + group);

UserPrincipal up = new UserPrincipal(ouContext);
if (de != null && isChecked == true)
{

de.Properties["member"].Add(up);
de.CommitChanges();
de.Close();
}
}

我算出来了。我用另一种方法解决了这个问题。而不是使用foreach循环遍历检查表中检查的每个项目。(我一直得到一个错误,认为列表已经更改,无法第二次循环。)我使用了foreach循环,它遍历所有选中的项,然后将它们放入字符串中,并将它们放入列表中。然后,我使用foreach循环遍历该列表(它不会改变),并从列表中获取字符串,并通过GroupName变量将它们传递给组主体。

var checkedItems = new List<string>();
foreach (var chk in chklbADGroups.CheckedItems)
{
checkedItems.Add(chk.ToString());
}
foreach (string GroupName in checkedItems)
{

WindowsIdentity.GetCurrent();
string username = up.SamAccountName;
MessageBox.Show(GroupName);
PrincipalContext context = new PrincipalContext(ContextType.Domain, DomainName);
GroupPrincipal grp = GroupPrincipal.FindByIdentity(context, IdentityType.Name, GroupName);
if (GroupName != null)
{
grp.Members.Add(context, IdentityType.SamAccountName, username);
grp.Save();
grp.Dispose();
context.Dispose();
}
}

最新更新