Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用C#代码从Active Directory获取当前登录_C#_.net_Active Directory - Fatal编程技术网

使用C#代码从Active Directory获取当前登录

使用C#代码从Active Directory获取当前登录,c#,.net,active-directory,C#,.net,Active Directory,如何使用C代码从Windows Active Directory获取当前用户的登录名 string Name = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).Identity.Name; 或 或 或 工作原理:)如果您使用的是.NET 3.5及更高版本,则可以使用: // set up domain context Principal

如何使用C代码从Windows Active Directory获取当前用户的登录名

string Name = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).Identity.Name;


工作原理:)

如果您使用的是.NET 3.5及更高版本,则可以使用:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find current user
UserPrincipal user = UserPrincipal.Current;

if(user != null)
{
   string loginName = user.SamAccountName; // or whatever you mean by "login name"
}    
新的S.DS.AM使得在广告中与用户和群组进行互动变得非常容易

参考资料:

  • (此链接已存档,)
这对我也很有用!谢谢

我得到了“NT授权\网络服务”,并提供了其他解决方案,但 System.Threading.Thread.CurrentPrincipal.Identity.Name.ToString()
为我工作。

我认为这对我来说非常合适


欢迎,@User.Identity.Name.Replace(“AD-GROUP-Name\\”,“”)。Replace(“.”,“”)

,所有涉及的广告在这里都是毫无用处的(它不会跟踪当前用户是谁-登录后,在会话期间不会问太多广告)。我有一个网站,我正在尝试将登录用户的用户名获取到Windows,但上述任何一项都没有告诉我:/谢谢。我一直在搜索。@Sunil你没有检查我的答案,有什么我能帮你的吗?你太棒了!谢谢大家!@user1306094:这适用于任何有Active Directory的环境。嗨,它在域内工作。如何使其在不同的服务器或外部工作Domain@user1306094:正如我已经说过的-它在Active Directory就位时工作。如果广告不存在,就没有办法让它发挥作用。不清楚为什么/您在不同服务器中的意思-它使用默认的Active Directory域工作-它没有绑定到特定的服务器您需要什么?'PrincipalContext ctx=new PrincipalContext(ContextType.DOMAIN);例如,以后不使用“ctx”时?@OleAlbers:在这种情况下,您不需要它。如果您想按某个名称搜索用户,则需要上下文。
string Name = Environment.GetEnvironmentVariable("USERNAME");
string Name = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find current user
UserPrincipal user = UserPrincipal.Current;

if(user != null)
{
   string loginName = user.SamAccountName; // or whatever you mean by "login name"
}    
System.DirectoryServices.AccountManagement.UserPrincipal.Current.Name