Tags

Very often you need SPUser but only have Full Name of the user. By using AD Search you can get user login name.

using System.DirectoryServices;



const string ADPATH = "LDAP://myLDAPserver,validUserforAD";
const string USERNAME = "myDomain\\myUserName";
const string PASSWORD = "myPassword";
const string DOMAIN = "myDomain\\";

public static DirectoryEntry GetDirectoryObject()
{
        DirectoryEntry directoryObject = new DirectoryEntry(ADPATH, USERNAME, PASSWORD, AuthenticationTypes.Secure);
        return directoryObject;
}


public string GetUserNameByCompleteName(string completeName)
{
            DirectoryEntry adObject = GetDirectoryObject();

            //filter based on complete name
            DirectorySearcher searcher = new DirectorySearcher(adObject);
            searcher.Filter = "displayname=" + completeName;
            SearchResult result = searcher.FindOne();

            DirectoryEntry userInfo = result.GetDirectoryEntry();

            //getting user name
            string userName = (string)userInfo.Properties["samaccountname"].Value ?? string.Empty;
            userInfo.Close();
            adObject.Close();

            return DOMAIN + userName;
}

SPUser user = web.Site.RootWeb.SiteUsers[loginName]
Advertisements