list all local users using directory services

后端 未结 2 1430
梦如初夏
梦如初夏 2021-02-06 02:26

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

NotSupportedException was unhandled...The provider does not su

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-06 02:59

    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 userNames = computerEntry.Children
            .Cast()
            .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);
    

提交回复
热议问题