Active Directory user name error in C#

0

I tried to display current user name in web appin c# but it is showing as error (Unknown error (0x80005000)) in the label that I try to display the user name in this label.

System.Security.Principal.IPrincipal User;
        User = System.Web.HttpContext.Current.User;
        string opl = User.Identity.Name;
        string username = GetFullName(opl);
        lblUserName.Text = username;

public static string GetFullName(string strLogin)
{
    string str = "";
    string strDomain = "MyDomain";
    string strName;

    // Parse the string to check if domain name is present.
    int idx = strLogin.IndexOf('\\');
    if (idx == -1)
    {
        idx = strLogin.IndexOf('@');
    }

    if (idx != -1)
    {
        strName = strLogin.Substring(idx + 1);
    }
    else
    {
        strName = strLogin;
    }

    DirectoryEntry obDirEntry = null;
    try
    {
        obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
        System.DirectoryServices.PropertyCollection coll = obDirEntry.Properties;
        object obVal = coll["FullName"].Value;
        str = obVal.ToString();
    }
    catch (Exception ex)
    {
        str = ex.Message;
    }
    return str;
}
c#
active-directory
asked on Stack Overflow Oct 15, 2014 by Anwar

1 Answer

0

You can do this much easier using the System.DirectoryServices.AccountManagement namespace:

using System.DirectoryServices.AccountManagement;

...

public static string GetFullName(string strLogin)
{
    using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
    using (UserPrincipal user = UserPrincipal.FindByIdentity(context, strLogin))
    {
        if (user == null) return string.Empty; // Do something else if user not found
        else return user.DisplayName;
    }
}
answered on Stack Overflow Oct 15, 2014 by Ashigore

User contributions licensed under CC BY-SA 3.0