我尝试在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;
}
答案 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;
}
}