简体   繁体   English

C#中的Active Directory用户名错误

[英]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. 我试图在Web App C#中显示当前用户名,但是在尝试在此标签中显示用户名的标签中显示为错误(未知错误(0x80005000))。

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: 您可以使用System.DirectoryServices.AccountManagement命名空间使此操作更加容易:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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