[英]How do I get the first name and last name of the logged in Windows user?
如何在系統中使用c#獲取我的姓氏(使用Active Directory用戶名登錄並通過Windows)?
是否可以不通過廣告就這樣做?
如果您使用的是.Net 3.0或更高版本,則有一個可愛的庫可以使它自己編寫。 System.DirectoryServices.AccountManagement
具有一個UserPrincipal
對象,該對象可以准確獲取您要查找的內容,而您無需弄亂LDAP或直接進行系統調用即可。 這就是全部:
Thread.GetDomain().SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal;
// or, if you're in Asp.Net with windows authentication you can use:
// WindowsPrincipal principal = (WindowsPrincipal)User;
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
{
UserPrincipal up = UserPrincipal.FindByIdentity(pc, principal.Identity.Name);
return up.DisplayName;
// or return up.GivenName + " " + up.Surname;
}
注意:如果已經有了用戶名,則實際上不需要主體,但是如果在用戶上下文中運行,從那里拉取它就很容易。
有一個更簡單的方法可以做到這一點:
using System.DirectoryServices.AccountManagement;
UserPrincipal userPrincipal = UserPrincipal.Current;
String name = userPrincipal.DisplayName;
這個解決方案對我不起作用,但是這個功能很好用:
public static string GetUserFullName(string domain, string userName)
{
DirectoryEntry userEntry = new DirectoryEntry("WinNT://" + domain + "/" + userName + ",User");
return (string)userEntry.Properties["fullname"].Value;
}
您應該這樣稱呼:
GetUserFullName(Environment.UserDomainName, Environment.UserName);
( 在這里找到)。
批准的答案的問題在於,如果您具有“姓氏,名字”策略,則DisplayName會給Smith,John而不是John Smith。 有兩種獲取正確格式的方法,userPrincipal.Name屬性包含“ John Smith(jsmith1)”,因此您可以使用它,而只是將string.Split放在“(”上。或者使用以下方法:
private string ConvertUserNameToDisplayName(string currentSentencedByUsername)
{
string name = "";
using (var context = new PrincipalContext(ContextType.Domain))
{
var usr = UserPrincipal.FindByIdentity(context, currentSentencedByUsername);
if (usr != null)
name = usr.GivenName+" "+usr.Surname;
}
if (name == "")
throw new Exception("The UserId is not present in Active Directory");
return name;
}
這將提供原始海報所需的“ John Smith”表格。
最快的方法是使用已經擁有的SID直接綁定到其AD對象。 例如:
//ASP.NET
var identity = (WindowsIdentity) HttpContext.Current.User.Identity;
//Desktop
var identity = WindowsIdentity.GetCurrent();
var user = new DirectoryEntry($"LDAP://<SID={identity.User.Value}>");
//Ask for only the attributes you want to read.
//If you omit this, it will end up getting every attribute with a value,
//which is unnecessary.
user.RefreshCache(new [] { "givenName", "sn" });
var firstName = user.Properties["givenName"].Value;
var lastName = user.Properties["sn"].Value;
有同樣的問題。 經過研究並瀏覽了Microsoft Docs,我找到了解決方案。
首先使用Nuget軟件包管理器安裝System.DirectoryServices.AccountManagement軟件包。
然后,在調用GetUserNameWithoutDomain方法時,將以下內容作為參數傳遞:
GetUserNameWithoutDomain(UserPrincipal.Current.GivenName, UserPrincipal.Current.Surname);
這絕對應該工作!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.