简体   繁体   中英

Active Directory user name error in C#

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;
}

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM