list all local users using directory services

左心房为你撑大大i 提交于 2020-06-24 07:37:48

问题


The following method I created seem does not work. An error always happens on foreach loop.

NotSupportedException was unhandled...The provider does not support searching and cannot search WinNT://WIN7,computer.

I'm querying the local machine

 private static void listUser(string computer)
 {
        using (DirectoryEntry d= new DirectoryEntry("WinNT://" + 
                     Environment.MachineName + ",computer"))
        {
           DirectorySearcher ds = new DirectorySearcher(d);
            ds.Filter = ("objectClass=user");
            foreach (SearchResult s in ds.FindAll())
            {

              //display name of each user

            }
        }
    }

回答1:


You cannot use a DirectorySearcher with the WinNT provider. From the documentation:

Use a DirectorySearcher object to search and perform queries against an Active Directory Domain Services hierarchy using Lightweight Directory Access Protocol (LDAP). LDAP is the only system-supplied Active Directory Service Interfaces (ADSI) provider that supports directory searching.

Instead, use the DirectoryEntry.Children property to access all child objects of your Computer object, then use the SchemaClassName property to find the children that are User objects.

With LINQ:

string path = string.Format("WinNT://{0},computer", Environment.MachineName);

using (DirectoryEntry computerEntry = new DirectoryEntry(path))
{
    IEnumerable<string> userNames = computerEntry.Children
        .Cast<DirectoryEntry>()
        .Where(childEntry => childEntry.SchemaClassName == "User")
        .Select(userEntry => userEntry.Name);

    foreach (string name in userNames)
        Console.WriteLine(name);
}       

Without LINQ:

string path = string.Format("WinNT://{0},computer", Environment.MachineName);

using (DirectoryEntry computerEntry = new DirectoryEntry(path))
    foreach (DirectoryEntry childEntry in computerEntry.Children)
        if (childEntry.SchemaClassName == "User")
            Console.WriteLine(childEntry.Name);



回答2:


The following are a few different ways to get your local computer name:

string name = Environment.MachineName;
string name = System.Net.Dns.GetHostName();
string name = System.Windows.Forms.SystemInformation.ComputerName;
string name = System.Environment.GetEnvironmentVariable(“COMPUTERNAME”);

The next one is a way to get the current user name:

string name = System.Windows.Forms.SystemInformation.UserName;


来源:https://stackoverflow.com/questions/8191696/list-all-local-users-using-directory-services

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!