查找本地域及域帐号详细信息(包含所属Group)
查找本地域及域帐号详细信息(包含所属Group)
1、获取当前域信息
2、获取当前登录的域帐号
3、使用域帐号查找该域帐号的详细信息
4、查找该域帐号所属分组信息(Group)
using System.DirectoryServices.AccountManagement; class Program { static void Main(string[] args) { //获取当前域 stringDomainName与stringDomainName的获取方式都可可 string stringDomainName = System.Environment.UserDomainName; //string stringDomainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName; //获取当前域帐号 string userName = System.Environment.UserName; PrincipalContext PrincipalContext1 = new PrincipalContext(ContextType.Domain, stringDomainName); UserPrincipal UserPrincipal1 = new UserPrincipal(PrincipalContext1); //按域帐号查找详细信息 UserPrincipal1.SamAccountName = userName; PrincipalSearcher search = new PrincipalSearcher(UserPrincipal1); UserPrincipal user = search.FindOne() as UserPrincipal; Console.WriteLine($@"SamAccountName-{user.SamAccountName}, DisplayName-{user.DisplayName}, Name-{user.Name}, GivenName-{user.GivenName}, Surname-{user.Surname}, Description-{user.Description}, Enabled-{user.Enabled}, LastLogon-{user.LastLogon}"); //获取所属分组信息 PrincipalSearchResultuserGroups = user.GetGroups(); foreach(var group in userGroups) { Console.WriteLine($"Group-{group.Name}"); } } }
参考资料:
https://docs.microsoft.com/en-us/previous-versions/bb384378(v=vs.90)?redirectedfrom=MSDN
https://www.codeproject.com/Articles/489348/Active-Directory-Users-and-Computers
https://www.coder.work/article/240074