C#中的Active Directory用户名错误

时间:2014-10-15 07:37:13

标签: c# active-directory

我尝试在web appin 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;
}

1 个答案:

答案 0 :(得分:0)

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