Monday, February 10, 2020

GET system display name, email or directory entry by login user id in C# by Dir DirectorySearcher




GET system display name, email or directory entry by login user id in C# by Dir DirectorySearcher


public class ActiveDirrectory
    {
        public static ADItems GetUserADDetails(string username)
        {
            try
            {
                DirectoryEntry dirEntry = new DirectoryEntry(Constants.LDAP);
                DirectorySearcher search = new DirectorySearcher(dirEntry);
                search.PropertiesToLoad.Add("cn");
                search.PropertiesToLoad.Add("displayName");
                search.PropertiesToLoad.Add("manager");
                search.PropertiesToLoad.Add("mail");
                search.PropertiesToLoad.Add("sAMAccountName");
                if (username.IndexOf('@') > -1)
                {
                    // userprincipal username
                    search.Filter = "(userPrincipalName=" + username + ")";
                }
                else
                {
                    // samaccountname username
                    String samaccount = username;
                    if (username.IndexOf(@"\") > -1)
                    {
                        samaccount = username.Substring(username.IndexOf(@"\") + 1);
                    }
                    search.Filter = "(sAMAccountName=" + samaccount + ")";
                }
                SearchResult result = search.FindOne();
                ADItems obj = new ADItems();
                if (result != null)
                {
                    obj.loginName = username;
                    if (result.Properties["displayName"] != null)
                        obj.displayName = Convert.ToString(result.Properties["displayName"][0]);                   
                    if (result.Properties["mail"] != null)
                        obj.email = Convert.ToString(result.Properties["mail"][0]);
                    if (result.Properties["manager"] != null)
                        obj.manager = Convert.ToString(result.Properties["manager"][0]);
                }
                return obj;
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
    }
    public class ADItems
    {
        public string loginName { get; set; }
        public string displayName { get; set; }
        public string email { get; set; }
        public string manager { get; set; }
    }

No comments:

Post a Comment