I can add a user perfectly well, but then I can't add it to a local group. I get this error:-
A member could not be added to or removed from the local group because the member does not exist.
Here is the code I'm using. What I am doing wrong? It's just the local machine, I definitely have rights to do it, and the group definifely exists.
try
{
using (DirectoryEntry hostMachineDirectory = new DirectoryEntry("WinNT://" + serverName))
{
DirectoryEntries entries = hostMachineDirectory.Children;
foreach (DirectoryEntry entry in entries)
{
if (entry.Name.Equals(userName, StringComparison.CurrentCultureIgnoreCase))
{
// Update password
entry.Invoke("SetPassword", password);
entry.CommitChanges();
return true;
}
}
DirectoryEntry obUser = entries.Add(userName, "User");
obUser.Properties["FullName"].Add("Used to allow users to login to Horizon. User created programmatically.");
obUser.Invoke("SetPassword", password);
obUser.Invoke("Put", new object[] {
"UserFlags",
0x10000
});
obUser.CommitChanges();
foreach (string group in groups)
{
DirectoryEntry grp = hostMachineDirectory.Children.Find(group, "group");
if (grp != null) { grp.Invoke("Add", new object[] { obUser.Path.ToString() }); }
}
return true;
}
}
catch (Exception ex)
{
returnMessage = ex.InnerException.Message;
return false;
}