2

我编写了一个程序,它打开与远程 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。

谢谢你的回答

4

1 回答 1

3

不确定这是否会有所帮助,但根据Microsoft Connect上的这份报告,这可能是相关的:

当前版本的 System.DirectoryServices.AccountManagement 组枚举要求组中的所有对象都可以访问,否则将引发异常。您看到的是本地组中列出的对象,该对象不再存在于 ActiveDirectory 中。由于系统不会自动删除这些链接,因此任何时候枚举该组都会失败。为防止出现此故障,请删除 ActiveDirectory 中不再存在的对象的链接。我们正在研究在未来的版本中对 API 进行更改,以使此类场景更易于处理。

于 2010-07-08T13:17:29.743 回答