Question

I wanted to query windows local user accounts from C# using ADSI. Since WinNt provider is used, Directory SEarcher is not supported. I am doing the following :

DirectoryEntries entries = hostMachineDirectory.Children;
var users = from DirectoryEntry childEntry in hostMachineDirectory.Children
                where (childEntry.Name.StartsWith("User1"))
                select childEntry;

Querying with Name is possible. It is not possible to get the description like childEntry.Description. It is possible to get the description by using properties childEntry.Properties["Description"].So is it possible to query with attributes like 'Description' ?

Was it helpful?

Solution

I don't know much about AD, but I guess, assuming that Properties["Description"].Value returns string, you can try it this way :

var users = from DirectoryEntry childEntry in entries
            where ((string)childEntry.Properties["Description"].Value).StartsWith("User1")
            select childEntry;

Ok since you confirmed that my assumption was wrong, Properties["Description"].Value doesn't always return string, it returns NULL sometimes, we need to check for null first before checking with .StartsWith or Contains or any other string checking operation :

var users = from DirectoryEntry childEntry in entries
            where childEntry.Properties["Description"].Value != null &&
                ((string)childEntry.Properties["Description"].Value).StartsWith("User1")
            select childEntry;

OTHER TIPS

If you are trying to get string, you should do it this way:

DirectoryEntries entries = hostMachineDirectory.Children;
var users = (from DirectoryEntry childEntry in hostMachineDirectory.Children
                where (childEntry.Name.StartsWith("User1"))
                select childEntry).SingleOrDefault<string>();

Here's how I got it to work.

var users = from DirectoryEntry childEntry in hostMachineDirectory.Children
            where childEntry.SchemaClassName == "User"
            select childEntry;
try { 
    var UserName = users.Single(s => s.Properties["Description"].Value.ToString().StartsWith("Whatever description")).Name;
    Console.WriteLine("User: " + UserName);
}
catch (Exception e) { 
    var err = e.Message;
    Console.WriteLine("Error message: " + err);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top