active directory - c#,为什么我不能添加域用户到本地组

本文关键字:用户 添加 不能 directory 为什么 active | 更新日期: 2023-09-27 17:49:20

为什么这段代码不起作用?我要做的是将域用户添加到本地组。

DirectorySearcher srch = new DirectorySearcher(new DirectoryEntry("LDAP://" + "AD1.test.it/DC=test,DC=it"));
srch.Filter = "(&(objectClass=user)(sAMAccountName=testUser))";            
SearchResultCollection results = srch.FindAll();
DirectoryEntry de = new DirectoryEntry(results[0].Path);
DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry dComUsersGrp = localMachine.Children.Find("Distributed COM Users", "group");
dComUsersGrp.Invoke("Add", new object[] { de.Path.ToString() }); 

我得到这个错误:"异常已被调用的目标抛出。"

类似的代码用于将本地用户添加到本地组。

DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry de = localMachine.Children.Find("testUser", "user");
DirectoryEntry dComUsersGrp = localMachine.Children.Find("Distributed COM Users", "group");
dComUsersGrp.Invoke("Add", new object[] { de.Path.ToString() });

非常感谢您的帮助

active directory - c#,为什么我不能添加域用户到本地组

string userPath = string.Format("WinNT://{0}/{1},user", domain, user);
string groupPath = string.Format("WinNT://{0}/{1},group", Environment.MachineName, group);
using (DirectoryEntry group = new DirectoryEntry(groupPath))
{
    group.Invoke("Add", userPath);
    group.CommitChanges();
}

您需要使用WinNT://ADSI命名空间

通常必须指定登录凭据才能访问目录。比如:

String domainAndUsername = domain + @"'" + username;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);