为什么这段代码不起作用?我想要做的是将域用户添加到本地组。
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() });
我收到此错误:“调用目标已抛出异常。”
Simillar代码适用于将本地用户添加到本地组中。
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() });
非常感谢您的帮助。
答案 0 :(得分:2)
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命名空间。
答案 1 :(得分:1)
您通常必须指定登录凭据才能访问该目录。类似的东西:
String domainAndUsername = domain + @"\" + username;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);