I've written a program which opens a connection to a remote Windows server in order to manage local accounts (not Active directory). The program executes the following steps:
- User Creation
- Add the user to a group
Both methods use System.DirectoryServices.AccountManagement, here the two functions:
public void CreateUser()
{
PrincipalContext pc = new PrincipalContext(ContextType.Machine,
"host_ip",
"adminaccount",
"adminpassword");
UserPrincipal up = new UserPrincipal(pc);
up.Name = "user";
up.DisplayName = "user";
up.SetPassword("user");
up.Description = "user";
up.UserCannotChangePassword = true;
up.PasswordNeverExpires = true;
try
{
up.Save();
}
catch (Exception ex)
{
}
try
{
AddToGroup(pc, up);
}
catch (Exception ex)
{
}
}
private void AddToGroup(PrincipalContext pc, UserPrincipal u)
{
string group = "Remote Desktop Users";
GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(pc, group);
if (groupPrincipal.Members.Contains(pc, IdentityType.SamAccountName, u.SamAccountName)) //error occurs here
{
return;
}
groupPrincipal.Members.Add(u);
try
{
开发者_如何学Go groupPrincipal.Save();
}
catch (Exception e)
{
}
}
It worked since this morning, the User creation always succeed but I'm getting this error at line:
- if (groupPrincipal.Members.Contains(pc, IdentityType.SamAccountName, u.SamAccountName))
An error (1332) occurred while enumerating the group membership. The member's SID could not be resolved.
Thanks for you answers
Not sure if this will help, but according to this report on Microsoft Connect, this could be related:
The current release of System.DirectoryServices.AccountManagement group enumeration has a requirement that all objects in the group are accessible or an exception will be thrown. What you are seeing is an object listed in the local group that no longer exists in ActiveDirectory. Since the system will not automatically remove these links, anytime this group is enumeratered it will fail. To prevent this failure remove the link to the object in ActiveDirectory that no longer exists. We are investigating making a change to the API in a future release that would make scenarios like this easier to deal with.
精彩评论