2011-10-01 30 views
3

远程机器上卸下的用户帐户我的代码:从管理员组使用C#和AccountManagment命名空间

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工作。但是当我再次运行我的应用程序时,我在我的列表视图中看到此用户。所以,用户没有被删除。

回答

2

我已经解决了没有AccountManagment命名空间的问题。

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; 
     } 
} 
+0

这也是我能枚举一些本地或远程机器级别组的唯一方法。当计算机级别组中存在域级别的主体时,AccountManagement名称空间会有一些问题。例如,将CORP \ myuser添加到本地管理员组将导致GroupPrincipal上的成员属性失败。 – jproch

0

下面的解决方法是删除与Directory Service帮助用户...

using System.DirectoryServices 

    private DeleteUserFromActiveDirectory(DataRow in_Gebruiker) 
    { 
      DirectoryEntry AD = new DirectoryEntry(strPathActiveDirectory , 
       strUsername, strPassword) 

      DirectoryEntry NewUser = 
       AD.Children.Find("CN=TheUserName", "User"); 

     AD.Children.Remove(NewUser); 
     AD.CommitChanges(); 
     AD.Close(); 
    } 
+0

此代码被删除的用户位于域中的用户组。但我需要从远程计算机上的管理员组中删除帐户。 – andDaviD

0

我不知道究竟是什么你的问题,但编码是这样的:

try 
{ 
    PrincipalContext context = new PrincipalContext(ContextType.Domain, "WM2008R2ENT:389", "dc=dom,dc=fr", "jpb", "passwd"); 

    /* Retreive a user principal 
    */ 
    UserPrincipal user = UserPrincipal.FindByIdentity(context, "user1"); 

    /* Retreive a group principal 
    */ 
    GroupPrincipal adminGroup = GroupPrincipal.FindByIdentity(context, @"dom\Administrateurs"); 

    foreach (Principal p in adminGroup.Members) 
    { 
    Console.WriteLine(p.Name); 
    } 

    adminGroup.Members.Remove(user); 
    adminGroup.Save(); 
} 
catch (Exception e) 
{ 
    Console.WriteLine(e.Message); 
} 

给我有以下例外情况:

Information about the domain could not be retrieved (1355) 

挖了一点点大地,告诉我我是在不在目标域上的计算机上运行我的代码。当我从服务器本身运行相同的代码时,它可以工作。看起来运行此代码的机器至少必须联系目标域的DNS。