问题
I created a Windows Form application to create an active directory user account in domain1 and aims to add it to the groups which are inside domain2. Here is the code I used:
PrincipalContext pc1 = new PrincipalContext(ContextType.Domain, "domain1.company.com", "DC=domain1,DC=company,DC=com", ContextOptions.Negotiate);
UserPrincipal up = new UserPrincipal(pc1, "username", "password", true);
up.Save();
PrincipalContext pc2 = new PrincipalContext(ContextType.Domain, "domain2.company.com", "DC=domain2,DC=company,DC=com", ContextOptions.Negotiate);
GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc2, "groupname");
gp.Members.Add(up);
gp.Save();
When I debug it in Visual Studio, the newly created user can be added to the group successfully. However, After I published and run it again, it returns error "There is no such object on the server".
Anyone know how to solve this?
Thank you.
回答1:
I worked on the same requirement, not so exactly, and we were required to process newly created user.
So, I tried two solutions -
Solution 1
Make thread to sleep for few milliseconds such as-
PrincipalContext pc1 = new PrincipalContext(ContextType.Domain, "domain1.company.com", "DC=domain1,DC=company,DC=com", ContextOptions.Negotiate);
UserPrincipal up = new UserPrincipal(pc1, "username", "password", true);
up.Save();
Thread.Sleep (500);
PrincipalContext pc2 = new PrincipalContext(ContextType.Domain, "domain2.company.com", "DC=domain2,DC=company,DC=com", ContextOptions.Negotiate);
GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc2, "groupname");
gp.Members.Add(up);
gp.Save();
This way, the AD is able to sync the user details in the entire domain and domain controller. And the user is found in next steps.
Solution 2
By default, the DirectoryEntry
object holds information about a user in the cache for performance reason. It doesn't reflect changes automatically.
So, we need to refresh the related cache by-
PrincipalContext pc1 = new PrincipalContext(ContextType.Domain, "domain1.company.com", "DC=domain1,DC=company,DC=com", ContextOptions.Negotiate);
UserPrincipal up = new UserPrincipal(pc1, "username", "password", true);
up.Save();
// Refresh cache so that we get updated user object
var de = (DirectoryEntry)up.GetUnderlyingObject();
de.RefreshCache();
PrincipalContext pc2 = new PrincipalContext(ContextType.Domain, "domain2.company.com", "DC=domain2,DC=company,DC=com", ContextOptions.Negotiate);
GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc2, "groupname");
gp.Members.Add(up);
gp.Save();
I recommend using Solution 2 if it works out fine.
来源:https://stackoverflow.com/questions/46782932/c-sharp-active-directory-add-user-to-group-in-another-domain