获取当前登录的Windows用户?

时间:2013-01-04 15:03:34

标签: .net windows winforms

  

可能重复:
  How to get the groups of a user in Active Directory? (c#, asp.net)

是否有办法使用System.DirectoryServices.AccountManagement命名空间获取当前登录的用户?我一直在使用以下内容:

    Dim wi As System.Security.Principal.WindowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent()

    Dim fullName As String = wi.Name.ToString

    Dim loggedOnUser = fullName.Substring(fullName.IndexOf("\") + 1)

    Console.WriteLine("The currently logged on user is {0}", loggedOnUser)

但是我想了解有关当前用户的更多信息,例如他们所属的组名称,并且想知道AccountManagement命名空间是否提供了此信息。

使用它只会返回我无法理解的数字字符串:

For Each item As IdentityReference In wi.Groups
    Console.WriteLine(item.ToString())
Next

1 个答案:

答案 0 :(得分:5)

你在寻找类似的东西吗?

using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "login");
    foreach (var group in user.GetGroups())
    {
        Console.WriteLine(group.Name);
    }
}

编辑:在stackoverflow的谷歌帮助下找到它;-) Active directory : get groups where a user is member