我创建了一个Windows窗体应用程序,用于在domain1中创建一个活动目录用户帐户,并旨在将其添加到domain2内的组。这是我使用的代码:
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();
当我在Visual Studio中调试它时,可以将新创建的用户成功添加到组中。但是,在我发布并再次运行它之后,它返回错误"There is no such object on the server".
任何人都知道如何解决这个问题?
谢谢。
答案 0 :(得分:0)
我处理相同的要求,而不是那么准确,我们被要求处理新创建的用户。
所以,我尝试了两种解决方案 -
使线程休眠几毫秒,例如 -
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();
这样,AD就能够在整个域和域控制器中同步用户详细信息。用户可以在后续步骤中找到。
默认情况下,出于性能原因,DirectoryEntry
对象保存有关缓存中用户的信息。它不会自动反映变化。
因此,我们需要通过 -
刷新相关的缓存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();
如果工作正常,我建议使用解决方案2.