2014-03-05 121 views
32

如何获取登录用户的显示名称?不是用户名,而是显示名称,如以下屏幕截图所示 - 并在任何Windows Vista/7计算机的开始菜单中显示。获取Windows用户显示名称

enter image description here

我尝试了一堆其他问题不同的意见,但他们都表现出了用户名,而不是显示名称。您可以在上面的截图中看到这些尝试的结果。

Imports System.Security.Principal 
Imports System.Threading 
Imports System.IO 
Imports System 

Public Class Form1 

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
     MsgBox("1: " & System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString & vbCrLf & _ 
       "2: " & Environment.UserDomainName & vbCrLf & _ 
       "3: " & WindowsIdentity.GetCurrent().Name & vbCrLf & _ 
       "4: " & Thread.CurrentPrincipal.Identity.Name & vbCrLf & _ 
       "5: " & Environment.UserName & vbCrLf & _ 
       "6: " & My.User.Name & vbCrLf & 
       "7: " & My.Computer.Name) 

    End Sub 

End Class 
+1

Environment.UserName在这里工作正常。 –

+0

没有。答案并不是我想要的。 – Codemunkeee

+0

在什么情况下使用'Environment.UserName'运行代码?它是在ASP.Net,Windows服务,正常的桌面应用程序等... – JaredPar

回答

52

你应该使用UserPrincipal.DisplayName

System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName 

要做到这一点,你需要从到System.DirectoryServices.AccountManagement.dll添加引用您的项目。

+0

最后,我的问题的正确答案。感谢您编辑我的问题! :d – Codemunkeee

+1

http://stackoverflow.com/a/6692790/3184380 – Shell

+6

我用这个方法,但在现实世界中,我看到了UserPrincipal.Current投掷PrincipalServerDownException,吸气。我相信这种情况是当前用户使用域帐户登录时,但无法联系目录服务器,例如从笔记本电脑拔出网络时。谨慎使用此方法,它似乎不可靠! –

-2

试试这个

http://msdn.microsoft.com/en-us/library/sfs49sw0(v=vs.110).aspx

using System.IO; 
using System; 
using System.Security.Principal; 
class Program 
{ 
    static void Main() 
    { 
     Console.WriteLine(WindowsIdentity.GetCurrent().Name); 
    } 
} 
+1

感谢..但它不工作:(( – Codemunkeee

+3

@Codemunkeee当描述一个问题,说:“它不工作”是没用的。为了得到对你有帮助告诉我们什么错误,你看到一个例外吗?如果是这样,什么是例外?是结果是否出乎预料?怎么会这样? –

+0

你可以参考我的问题之上。正如你可以看到它返回一个不同的输出,我我将再次编辑代码以列出我所做的所有事情。 – Codemunkeee

-2

System.DirectoryServices程序集必须先导入。 System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName 它返回在开始菜单(不是系统登录ID)中显示的显示名称。 谢谢蒂姆。

相关问题