2010-08-12 159 views

回答

47

如果您使用的是.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; 
} 

注意:你實際上並不需要的本金,如果你已經擁有了用戶名,但如果你的用戶上下文中運行,它只是簡單從拉那裏。

+0

.Net2呢? – 2010-08-13 10:02:15

+0

升級?是的,我知道,沒有幫助。抱歉。我從來沒有滿意於在早期版本的框架中爲了從AD中獲取信息而必須經歷的環節。 – 2010-08-13 16:03:10

+5

['PrincipalContext'](http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.principalcontext.aspx)似乎已經在.NET 3.5中引入了 – 2011-06-13 14:59:57

8

該解決方案並沒有爲我工作,但這一功能極大的努力:

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

(發現here)。

+0

等一下,這個解決方案是什麼意思。如果你的意思是你自己的答案,那你爲什麼要發佈它?如果你的意思是另一種解決方案,請澄清哪一個。 – TylerH 2018-02-01 20:33:02

42

還有就是要做到這一點更簡單的方法:

using System.DirectoryServices.AccountManagement; 

UserPrincipal userPrincipal = UserPrincipal.Current; 
String name = userPrincipal.DisplayName; 

enter image description here

相關問題