gpt4 book ai didi

c# - 从 Active Directory 检索用户名

转载 作者:太空宇宙 更新时间:2023-11-03 12:36:34 25 4
gpt4 key购买 nike

我正在尝试从 Active Directory 中检索用户名。我找到了这段代码来尝试,但是它无法识别 User.Identity.NameUser 部分。我查看是否需要添加另一个引用或程序集,但我没有看到任何东西。有没有更好的方法从 Active Directory 获取用户名?

static string GetUserName(){

string name = "";
using (var context = new PrincipalContext(ContextType.Domain))
{
var usr = UserPrincipal.FindByIdentity(context, User.Identity.Name);
if (usr != null)
name = usr.DisplayName;
}

}

最佳答案

您可以使用 WindowsIdentity.GetCurrent

using System.Security.Principal;

static string GetUserName()
{
WindowsIdentity wi = WindowsIdentity.GetCurrent();

string[] parts = wi.Name.Split('\\');

if(parts.Length > 1) //If you are under a domain
return parts[1];
else
return wi.Name;
}

用法:

string fullName = GetUserName();

很高兴为您服务!

关于c# - 从 Active Directory 检索用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40771469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com