title: How to retrieve SAMAccountName from Active Directory
body: <p>I implemented a method that returns a list of Active Directory users, I would like to retrieve SAMAccountName like this <code>Domain\Administrator</code>.</p>
  
  <p>This is the method I use: </p>
  
  <pre><code>public Collection&lt;software_user&gt; GetUsersFromAD(String adConnectionString)
  {
      var users = new Collection&lt;software_user&gt;();
  
      using (var directoryEntry = new DirectoryEntry(adConnectionString))
      {
          var directorySearcher = new DirectorySearcher(directoryEntry);
          directorySearcher.Filter = "(&amp;(objectClass=user))";
          var propertiesToLoad = new[] 
          { 
             "SAMAccountName", 
             "displayName", 
             "givenName", 
             "sn", 
             "mail", 
             "userAccountControl", 
             "objectSid" 
          };
          directorySearcher.PropertiesToLoad.AddRange(propertiesToLoad);
  
          foreach (SearchResult searchEntry in directorySearcher.FindAll())
          {
              var userEntry = searchEntry.GetDirectoryEntry();
              var ldapUser = new software_user();
              ldapUser.User_name = NullHandler.GetString(userEntry.Properties["displayName"].Value);
  
              if (string.IsNullOrEmpty(ldapUser.User_name))
                 continue;
              ldapUser.User_name = NullHandler.GetString(userEntry.Properties["SAMAccountName"].Value);
              ldapUser.email = NullHandler.GetString(userEntry.Properties["mail"].Value);
              ldapUser.user_shortname = NullHandler.GetString(userEntry.Properties["givenName"].Value);
              var userAccountControl = (int)userEntry.Properties["userAccountControl"].Value;
              //ldapUser.IsActive = (userAccountControl &amp; UF_ACCOUNTDISABLE) != UF_ACCOUNTDISABLE;
              var sid = new SecurityIdentifier((byte[])userEntry.Properties["objectSid"][0], 0).Value;
              //ldapUser.SId = sid;
              users.Add(ldapUser);
           }
      }
      return users;
  }
  </code></pre>