开发者

C#, why I can't add domain user into local group?

开发者 https://www.devze.com 2023-02-23 03:16 出处:网络
Why this code doesn work ? What I want to do is add domain user into local group. DirectorySearcher srch = new DirectorySearcher(new DirectoryEntry(\"LDAP://\" + \"AD1.test.it/DC=test,DC=it\"));

Why this code doesn work ? What I want to do is add domain user into local group.

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() }); 

I get this error: "Exception has been thrown by the target of an invocation."

Simillar code works for adding local user into a local group.

DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry de = localMachine.Children.Find("testUser", "user");

DirectoryEntry dComUsersG开发者_运维知识库rp = localMachine.Children.Find("Distributed COM Users", "group");
dComUsersGrp.Invoke("Add", new object[] { de.Path.ToString() });

Thank you very much for any help.


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();
}

You need to use WinNT:// ADSI namespace.


You usually have to specify logon credentials to access the directory. Something like:

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

精彩评论

暂无评论...
验证码 换一张
取 消