如何使用Ipaddress或主机名查找用户名?

时间:2019-01-03 04:44:30

标签: c# windows username directoryservices

我使用活动目录找到了Ipaddress和主机名 ComputerPrincipal方法。但是在此方法中找不到用户名。我需要我域中的用户名。该怎么做?

这是我的代码

namespace Directory
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new PrincipalContext(ContextType.Domain, "xxx.com"))
            {
                using (var searcher = new PrincipalSearcher(new ComputerPrincipal(context)))
                {
                    foreach (var result in searcher.FindAll())
                    {
                        var auth = result as AuthenticablePrincipal;
                        if (auth != null)
                        {
                            Console.WriteLine("Name: " + auth.Name);
                            Console.WriteLine("Last Logon Time: " + auth.LastLogon);
                            if (auth.Name != "Txx-Cxx-Gxx-Pxx")
                            {
                                IPAddress[] ipaddress = Dns.GetHostAddresses(auth.Name);
                                foreach (IPAddress ipaddr in ipaddress)
                                {
                                    Console.WriteLine(ipaddr);
                                }

                                Console.WriteLine();
                            }
                            else
                            {
                                Console.WriteLine("Error");
                            }
                        }
                    }
                }
            }

2 个答案:

答案 0 :(得分:1)

使用UserPrincipalName类的AuthenticablePrincipal属性。
例如:

   var auth = result as AuthenticablePrincipal;
   var userName = auth.UserPrincipalName;

请参见hereAuthenticablePrincipal具有的所有属性,方法等。

答案 1 :(得分:0)

要获取Windows登录用户

string m_strUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

请参考WindowsIdentity

提供的其他详细信息