如何在我的系统中使用c#获取我的名字姓氏(使用Active Directory用户名和密码登录Windows)?
是否有可能在不去AD的情况下做到这一点?
如何获取登录用户的显示名称?不是用户名,而是显示名称,如下面的屏幕截图所示 - 以及任何Windows Vista/7计算机的开始菜单中显示的名称.

我从其他问题尝试了一堆不同的建议,但它们都显示了用户名,而不是显示名称.您可以在上面的屏幕截图中看到这些尝试的结果.
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 & _ …Run Code Online (Sandbox Code Playgroud) 我需要获取当前用户的显示名称,并找不到始终有效的解决方案.为了清楚起见,我不是在寻找用户名.我需要"John Doe"."开始"菜单上显示的值.
关于这个问题有很多帖子,但没有一个解决了我的问题.
这两个帖子引导我:
PrincipalContext context = domain.Equals(Environment.MachineName, StringComparison.CurrentCultureIgnoreCase) ?
new PrincipalContext(ContextType.Machine) :
new PrincipalContext(ContextType.Domain, domain);
UserPrincipal userPrincipal = new UserPrincipal(context) { SamAccountName = username };
PrincipalSearcher searcher = new PrincipalSearcher(userPrincipal);
userPrincipal = searcher.FindOne() as UserPrincipal;
string displayName = userPrincipal.DisplayName;
Run Code Online (Sandbox Code Playgroud)
这段代码大部分都适用.但是,如果用户已在其计算机上禁用/停止了服务器服务,则会出现"服务器服务未启动"的异常.
System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName
Run Code Online (Sandbox Code Playgroud)
同样的错误.
StringBuilder name = new StringBuilder(1024);
uint userNameSize = (uint)name.Capacity;
const int NameDisplay = 3;
GetUserNameEx(NameDisplay, name, ref userNameSize)
Run Code Online (Sandbox Code Playgroud)
不返回错误,但如果用户不在域中,则返回空字符串.
如何可靠地在所有版本的Windows上读取用户的显示(第一个和最后一个)名称?
// get SAM compatible name <server/machine>\\<username>
if (0 != GetUserNameEx(2, username, ref userNameSize))
{ …Run Code Online (Sandbox Code Playgroud) 我发现在Windows 7 64位上,在具有域名的机器上,GetUserNameEx(3,....)应该将扩展名称格式DisplayName(== 3)放入缓冲区,工作正常.
但是,它不适用于Windows 7 32位,工作组上的虚拟机,而不是域,它返回ERROR_NONE_MAPPED.
例如,你如何以适用于Windows的方式阅读该人的友好名称"Fred Smith"?GetUserNameEx明显被破坏了.实际上,没有破坏,我被告知,只是不打算为不在域上的用户工作.我想知道为什么不存在本地SAM信息?并且似乎没有其他直接API来执行此操作.
如果Windows为您提供ERROR_NONE_MAPPED,那么您运气不佳,可能不在域上.所以这不是API的友好区域.
[看起来有可能,调用NetUserGetInfo,读取本地SAM信息,当不在域上时,但您需要首先知道用户名和密码,然后它可能会查找友好名称.]
给出下面的代码,lastuser 字符串返回空值,但是,如果我使用 regedit 查看这个键,它有与之关联的数据。LoggedOnSAMuser 是受限密钥吗?
public static string lastlogon()
{
string lastuser;
RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI",false);
if (registryKey != null)
{
lastuser = (string) registryKey.GetValue("LastLoggedOnSAMUser");
}
else lastuser = "Unknown User";
return (lastuser);
}
Run Code Online (Sandbox Code Playgroud)