private static string GetUPN(string accountType, string samaccountname)
{
string ldapQuery = ConfigurationManager.AppSettings["LocalAdLdapQuery"].ToString();
// Bind to the users container.
DirectoryEntry entry = new DirectoryEntry(ldapQuery);
// Create a DirectorySearcher object.
DirectorySearcher mySearcher = new DirectorySearcher(entry);
// Create a SearchResultCollection object to hold a collection of SearchResults
// returned by the FindAll method.
mySearcher.PageSize = 500; // ADD THIS LINE HERE !
string strFilter = string.Empty;
if (accountType.ToLower().Equals("user"))
strFilter = string.Format("(&(objectCategory=User)(SAMAccountName={0}))", samaccountname);
else if (accountType.ToLower().Contains("group"))
strFilter = string.Format("(&(objectCategory=Group)(sid={0}))", samaccountname);
var propertiesToLoad = new[] { "SAMAccountName", "userprincipalname", "sid" };
mySearcher.PropertiesToLoad.AddRange(propertiesToLoad);
mySearcher.Filter = strFilter;
mySearcher.CacheResults = false;
SearchResultCollection result = mySearcher.FindAll();
if (result.Count > 0)
{
return GetProperty(result[0], "userprincipalname");
}
return string.Empty;
}