使用C#和AccountManagment命名空间从远程计算机管理员组中删除用户帐户帐户、组中、管理员、计算机

2023-09-09 21:34:48 作者:最初的梦想

我有code:

 public bool RemoveUserFromAdministratorsGroup(UserPrincipal oUserPrincipal, string computer)
 {
        try
        {
            PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine, computer, null, ContextOptions.Negotiate, _sServiceUser, _sServicePassword);
            GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, "Administrators");

            oGroupPrincipal.Members.Remove(oUserPrincipal);
            oGroupPrincipal.Save();

            return true;
        }
        catch
        {
            return false;
        }

 }

据工作没有任何excaption。但是,当我跑我的应用程序,我再次看到我的ListView该用户。因此,用户是不会被删除。

It is worked without any excaption. But when i run my app again i see this user in my listview. So, the user wasn't removed.

推荐答案

我已经解决了这个问题,而不AccountManagment命名空间。

I have solved the issue without AccountManagment namespace.

 public bool RemoveUserFromAdminGroup(string computerName, string user)
 {
        try
        {
            var de = new DirectoryEntry("WinNT://" + computerName);
            var objGroup = de.Children.Find(Settings.AdministratorsGroup, "group");

            foreach (object member in (IEnumerable)objGroup.Invoke("Members"))
            {
                using (var memberEntry = new DirectoryEntry(member))
                    if (memberEntry.Name == user)
                        objGroup.Invoke("Remove", new[] {memberEntry.Path});
            }

            objGroup.CommitChanges();
            objGroup.Dispose();

            return true;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
            return false;
        }
 }