List of all local users using directory services

The next method I created does not seem to work. The error always occurs in the foreach loop.

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

I am requesting a 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

            }
        }
    }
+5
source share
2 answers

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

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);
+13
source

:

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

- :

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

All Articles