Hello stackoverflow,
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
{
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