ikel ikel - 2 months ago 34
C# Question

list all local users using directory services

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

}
}
}

Answer

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

With LINQ:

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

using (var computerEntry = new DirectoryEntry(path))
{
    var userNames = from DirectoryEntry childEntry in computerEntry.Children
                    where childEntry.SchemaClassName == "User"
                    select childEntry.Name;

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

Without LINQ:

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

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