2011-10-01 62 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。