我编写了一个程序,它打开与远程 Windows 服务器的连接以管理本地帐户(不是 Active Directory)。该程序执行以下步骤:
- 用户创建
- 将用户添加到组
两种方法都使用 System.DirectoryServices.AccountManagement,这里有两个功能:
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)
{
}
}
它从今天早上开始工作,用户创建总是成功,但我遇到了这个错误:
- if (groupPrincipal.Members.Contains(pc, IdentityType.SamAccountName, u.SamAccountName))
枚举组成员身份时发生错误 (1332)。无法解析成员的 SID。
谢谢你的回答