2012-05-22 23 views
9

Estoy usando las clases System.DirectoryServices.ActiveDirectory para encontrar todos los usuarios de Active Directory. El código es muy simple:¿Dónde está el nombre de dominio en un objeto UserPrincipal?

var context = new PrincipalContext(ContextType.Domain); 
var searcher = new PrincipalSearcher(new UserPrincipal(context)); 
var results = searcher.FindAll(); 

que desea obtener el nombre de usuario de dominio cualificado en el (formato conocido como "pre-Windows 2000".) "Amigable", por ejemplo. "CONTOSO \ SmithJ". UserPrincipal.SamAccountName me da la parte de nombre de usuario, pero ¿cómo obtengo la parte de dominio? No puedo suponer que el dominio será el mismo que el de la máquina o el dominio actual del usuario.

+0

Posible duplicado: http://stackoverflow.com/questions/4284641/get-netbiosname-from- a-userprincipal-object – MichelZ

Respuesta

6

Para AD DS, el valor de msDS-PrincipalName es el nombre de dominio de NetBIOS, seguido de una barra invertida ("\").

usted lo puede encontrar usando:

/* Retreiving the root domain attributes 
*/ 
sFromWhere = "LDAP://DC_DNS_NAME:389/dc=dom,dc=fr"; 
DirectoryEntry deBase = new DirectoryEntry(sFromWhere, "AdminLogin", "PWD"); 

DirectorySearcher dsLookForDomain = new DirectorySearcher(deBase); 
dsLookForDomain.Filter = "(objectClass=*)"; 
dsLookForDomain.SearchScope = SearchScope.base; 
dsLookForDomain.PropertiesToLoad.Add("msDS-PrincipalName"); 

SearchResult srcDomains = dsLookForDomain.FindOne(); 
+0

+1 Gracias, msDS-PrincipalName parece lo que quiero. – EMP

+0

NOTA: podría ser el Domain \ Username O el SID del usuario según MSDN: http://msdn.microsoft.com/en-us/library/cc223404.aspx –

0

OK, aquí está el código final se me ocurrió usar la respuesta de JPBlanc y la answer linked by MichaelZ. Muestra el SID, el nombre para mostrar y el DOMINIO \ nombre de usuario para cada usuario.

var ldapUrl = "LDAP://" + defaultNamingContext; 

    using (var rootDe = new DirectoryEntry(ldapUrl)) 
    using (var searcher = new DirectorySearcher(rootDe)) 
    { 
     searcher.SearchScope = SearchScope.Subtree; 
     searcher.PropertiesToLoad.Add("objectSid"); 
     searcher.PropertiesToLoad.Add("displayName"); 
     searcher.PropertiesToLoad.Add("msDS-PrincipalName"); 
     searcher.Filter = "(&(objectClass=user)(objectCategory=person))"; 

     var results = searcher.FindAll(); 

     foreach (SearchResult result in results) 
     { 
      var qualifiedUsername = GetSinglePropertyValue(result, "msDS-PrincipalName"); 
      var displayName = GetSinglePropertyValue(result, "displayName"); 
      var sid = new SecurityIdentifier((byte[])GetSinglePropertyValue(result,"objectSid"), 0); 

      Console.WriteLine("User: {0}\r\n\tDisplay name: {1}\r\n\tSID: {2}", 
       qualifiedUsername, displayName, sid); 
     } 
    } 

    private static object GetSinglePropertyValue(SearchResult result, string propertyName) 
    { 
     var value = result.Properties[propertyName]; 
     if (value.Count == 0) 
      return null; 
     if (value.Count == 1) 
      return value[0]; 
     throw new ApplicationException(string.Format("Property '{0}' has {1} values for {2}", 
      propertyName, value.Count, result.Path)); 
    } 

Y para obtener el contexto de nomenclatura predeterminado para el dominio de la máquina (como answered here):

private static string GetDefaultNamingContext() 
{ 
    // This check is fast 
    try 
    { 
     Domain.GetComputerDomain(); 
    } 
    catch (ActiveDirectoryObjectNotFoundException) 
    { 
     return null; 
    } 

    // This takes 5 seconds if the computer is not on a domain 
    using (var rootDe = new DirectoryEntry("LDAP://RootDSE")) 
    { 
     try 
     { 
      return (string)rootDe.Properties["defaultNamingContext"][0]; 
     } 
     catch (COMException ex) 
     { 
      if (ex.ErrorCode == -2147023541) 
       return null; 
      throw; 
     } 
    } 
} 
Cuestiones relacionadas