Question

I am trying to wrap my head around LINQ, so I can figure out how to query the DirectoryEntry. At the moment I am trying to write some code in C# that will take a string variable and gave a list of member within a group based upon this string.

Below is what I have managed to figure out so far

public static string[] GetAllUsersInGroup(string groupname)
{
    var names = new List<string>();
    var path = string.Format("WinNT://{0},computer", Environment.MachineName);
    var computerEntry = new DirectoryEntry(path);

    if (computerEntry != null)
    {
        using (computerEntry)
        {
            var menberNames = from DirectoryEntry childEntry
                                in computerEntry.Children.Find("testgroup", "group")
                              where childEntry.SchemaClassName == "User"
                              select childEntry.Name;

            foreach (var name in memberNames)
            {
                names.Add(name);
            }
        }
    }

    return names.ToArray();
}

The problem with this is that I can't use Children.Find() in the where statement.

Although I would like to know how to do this correctly, I really want to be able to figure this out, since there are other queries I need to do. So if anyone know of any GOOD source to find this info please let me know

Was it helpful?

Solution

I am not really sure about this. Try if it works for you.

public static string[] GetAllUsersInGroup(string groupname)
{
    var path = string.Format("WinNT://{0},computer", Environment.MachineName);

    using (var computerEntry = new DirectoryEntry(path))
    {
        if (computerEntry != null)
        {
            return
                computerEntry.Children.SelectMany(childEntry => 
                    ChildEntry.Children.Find("Administrators", "group")
                        .Children.Select(child => child.Name))
                    .ToArray();
        }
        else 
        {
            return null;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top