C# .NET - Get all Group Names in Activedirectory using C#

Asked By suresh G on 21-Jan-09 06:40 AM

HI


I need to display all group names in activedirectory using C# and asp.net 

can anyone suggest me on this


Thanks

RE

Web Star replied to suresh G on 21-Jan-09 06:45 AM

Complete C# code:
-------------------

using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Threading;

namespace ADQuery
{
    class Program
    {
        static void Main(string[] args)
        {
            string output = String.Empty;
            Process DESProcess = new Process();
            string privilegesGroup = "admin-group"; //Provide any group name for which you want to see members
            DESProcess.StartInfo.FileName = @"C:\WINNT\system32\cmd.exe";
            DESProcess.StartInfo.Arguments = " /c DSQUERY USER -samid " + privilegesGroup + " | DSGET USER -memberof";
            DESProcess.StartInfo.CreateNoWindow = true;
            DESProcess.StartInfo.UseShellExecute = false;
            DESProcess.StartInfo.RedirectStandardInput = true;
            DESProcess.StartInfo.RedirectStandardOutput = true;
            DESProcess.StartInfo.WorkingDirectory = ".";
            DESProcess.StartInfo.RedirectStandardError = true;
            DESProcess.Start();

            while (DESProcess.StandardOutput.Peek() > -1)
                output = output + (DESProcess.StandardOutput.ReadToEnd()).ToString();

            DESProcess.StandardOutput.DiscardBufferedData();

            System.Console.WriteLine(output);
            System.Console.Read();
        }
    }
}

http://www.codeproject.com/KB/system/everythingInAD.aspx

http://support.microsoft.com/kb/316748

Get all Group Names in Activedirectory using C#

mv ark replied to suresh G on 21-Jan-09 06:52 AM
You will need to use the System.DirectoryServices namespace

There is a code sample here -
http://stackoverflow.com/questions/323536/asp-net-how-to-get-list-of-groups-in-active-directory

Get all Group Names in Activedirectory using C#

Kalit Sikka replied to suresh G on 21-Jan-09 07:07 AM
using System;
using System.Collections;
using System.Windows.Forms;
using System.DirectoryServices;
namespace ADgroupSearcher
{
    class getGroupMembers
    {
        /// <summary>
        /// searchedGroups will contain all groups already searched, in order to
        /// prevent endless loops when there are circular structured in the groups.
        /// </summary>
        static Hashtable searchedGroups = null;
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] argv)
        {
            Console.WriteLine("Searching");
            try
            {
                ArrayList nested_group_members = GetNestedGroupsUsers(argv[0]);
                foreach (string str in nested_group_members)
                {
                    Console.WriteLine(str);
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("Exception : " + ex.Message);
            }
            Console.WriteLine("Press any key to exit..");
            Console.Read();
        }
        /// <summary>
        /// x will return all users in the group passed in as a parameter
        /// the names returned are the SAM Account Name of the users.
        /// The function will recursively search all nested groups.
        /// Remark: if there are multiple groups with the same name, this function will just
        /// use the first one it finds.
        /// </summary>
        /// <param name="strGroupName">Name of the group, which the users should be retrieved from</param>
        /// <returns>ArrayList containing the SAM Account Names of all users in this group and any nested groups</returns>
        static public ArrayList GetNestedGroupsUsers(string strGroupName)
        {
            ArrayList groupMembers = new ArrayList();
            searchedGroups = new Hashtable();
            // find group
            DirectorySearcher search = new DirectorySearcher("LDAP://DC=company,DC=com");
            search.Filter = String.Format("(&(objectCategory=group)(cn={0}))", strGroupName);
            search.PropertiesToLoad.Add("distinguishedName");
            SearchResult sru = null;
            DirectoryEntry group;
            try
            {
                sru = search.FindOne();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            group = sru.GetDirectoryEntry();
            groupMembers = getUsersInGroup(group.Properties["distinguishedName"].Value.ToString());
            return groupMembers;
        }
        /// <summary>
        /// getUsersInGroup will return all users in the group passed in as a parameter
        /// the names returned are the SAM Account Name of the users.
        /// The function will recursively search all nested groups.
        /// </summary>
        /// <param name="strGroupDN">DN of the group, which the users should be retrieved from</param>
        /// <returns>ArrayList containing the SAM Account Names of all users in this group and any nested groups</returns>
        private static ArrayList getUsersInGroup(string strGroupDN)
        {
            ArrayList groupMembers = new ArrayList();
            searchedGroups.Add(strGroupDN, strGroupDN);
            // find all users in this group
            DirectorySearcher ds = new DirectorySearcher("LDAP://DC=company,DC=com");
            ds.Filter = String.Format("(&(memberOf={0})(objectClass=person))", strGroupDN);            
            ds.PropertiesToLoad.Add("samaccountname");
            try
            {
                foreach (SearchResult sr in ds.FindAll())
                {
                    Console.WriteLine(sr.Properties["samaccountname"][0].ToString());
                }
            }
            catch {
                //ignore if any properties found in AD
            }
            // get nested groups
            ArrayList al = getNestedGroups(strGroupDN);
            foreach (object g in al)
            {
                if (!searchedGroups.ContainsKey(g)) // only if we haven't searched this group before - avoid endless loops
                {
                    // get members in nested group
                    ArrayList ml = getUsersInGroup(g as string);
                    // add them to result list
                    foreach (object s in ml)
                    {
                        Console.WriteLine(s as string);
                    }
                }
            }
            return groupMembers;
        }
        /// <summary>
        /// getNestedGroups will return an array with the DNs of all groups contained
        /// in the group that was passed in as a parameter
        /// </summary>
        /// <param name="strGroupDN">DN of the group, which the nested groups should be retrieved from</param>
        /// <returns>ArrayList containing the DNs of each group contained in the group apssed in asa parameter</returns>
        private static ArrayList getNestedGroups(string strGroupDN)
        {
            ArrayList groupMembers = new ArrayList();
            // find all nested groups in this group
            DirectorySearcher ds = new DirectorySearcher("LDAP://DC=company,DC=com");
            ds.Filter = String.Format("(&(memberOf={0})(objectClass=group))", strGroupDN);
            ds.PropertiesToLoad.Add("distinguishedName");
            foreach (SearchResult sr in ds.FindAll())
            {
                groupMembers.Add(sr.Properties["distinguishedName"][0].ToString());
            }
            return groupMembers;
        }
    }
}
Getting User Groups from Active Directory
C_A P replied to suresh G on 22-Jan-09 02:30 AM

Setup:

1. In http://www.wwwcoder.com/Directory/tabid/68/type/art/site/5946/parentid/272/Default.aspx# go into Security and instead of using the default IIS username and password you have to add a valid username and password.

2. Add a reference to System.DirectoryServices and at the top of the codebehind add "Imports System.DirectoryServices" 

Code:  

Private Sub Page_Load(ByVal sender As System.Object, ByVal e _
    As System.EventArgs) Handles MyBase.Load
    Response.Write(GetGroups("LDAP://domainname", "username", "password"))
    'Returns String of: "Group1|Group2|Group3|"
End Sub
   
Private Function GetGroups(ByVal _path As String, ByVal _
     username As String, ByVal password As String) As String
    Dim GroupString As String
    Dim myDE As New System.DirectoryServices.DirectoryEntry(_path, _
      username, password)     

    Dim mySearcher As New DirectorySearcher(myDE)

    mySearcher.Filter = "sAMAccountName=" & username
    mySearcher.PropertiesToLoad.Add("memberOf")
    Dim propertyCount As Integer

    Try

        Dim myresult As SearchResult = mySearcher.FindOne()
        propertyCount = myresult.Properties("memberOf").Count
          
        Dim dn As String
        Dim equalsIndex, commaIndex As String

        For i As Integer = 0 To propertyCount - 1
            dn = myresult.Properties("memberOf")(i)
            equalsIndex = dn.IndexOf("=", 1)
            commaIndex = dn.IndexOf(",", 1)
            If equalsIndex = -1 Then
                Return Nothing
            End If

            GroupString += dn.Substring((equalsIndex + 1), _
              (commaIndex - equalsIndex) - 1) & "|"

        Next
        Return GroupString

    Catch ex As Exception
        If ex.GetType Is GetType(System.NullReferenceException) Then
            Response.Write("does not have a group")

            'they are still a good user just does not
            'have a "memberOf" attribute so it errors out.
            'code to do something else here if you want

        Else
            Response.Write(ex.Message.ToString & ex.ToString)
        End If 
    End Try 

 End Function

active directory group lookup
C_A P replied to suresh G on 22-Jan-09 02:31 AM

 

Public Function Groups(ByVal SearchResult As System.DirectoryServices.SearchResult) As String
    Dim i As Integer
    Dim tmp As String
    Dim groupSid As Object
    Dim sid() As Byte
    Try
        Dim de As DirectoryEntry = SearchResult.GetDirectoryEntry
        'pull username and password from web.config file.
        de.Username = Configuration.ConfigurationSettings.AppSettings("User")
        de.Password = Configuration.ConfigurationSettings.AppSettings("Pass")
        de.RefreshCache(New String() {"tokenGroups"})
        'this line is sometimes necessary to get tokenGroups in the property cache...
        'loop through each sid in the tokenGroups
        For Each groupSid In de.Properties("tokenGroups")
            'just another way of doing a ctype.
            sid = DirectCast(groupSid, Byte())
            'set up the groupentry for query
            'ConvertToOctetString is the important part here. This is where the real work is.
            Dim groupEntry As New DirectoryEntry(String.Format("LDAP://", ConvertToOctetString(sid)))
            Dim propcoll As PropertyCollection = groupEntry.Properties
            Dim key As String
            Dim values As Object

            'loop through all of the properties for this record
            For Each key In propcoll.PropertyNames
                'loop through all the values associated with our key
                For Each values In propcoll(key)
                    If LCase(key) = "distinguishedname" Then
                      Dim temp As String = values.ToString
                      If Not InStr(temp, "ImportedExchange") Then
                        Dim atemp() As String = temp.Split(",")
                        tmp &= Replace(atemp(0).ToString, "CN=", ",")
                        If Left(tmp, 1) = "," Then
                            tmp = Mid(tmp, 2)
                        End If
                      End If
                    End If
                Next
            Next
        Next

    Catch ex As Exception
        'process exception
    End Try

    Return tmp
End Property

'overload for lazy http://www.wwwcoder.com/parentid/272/tabid/68/type/art/site/2208/default.aspx
Public Overloads Shared Function ConvertToOctetString(ByVal values As Byte()) As String
    Return ConvertToOctetString(values, False, False)
End Function

'overload for lazy programming
Public Overloads Shared Function ConvertToOctetString(ByVal values As Byte(), _
     ByVal isAddBackslash As Boolean) As String
    Return ConvertToOctetString(values, isAddBackslash, False)
End Function

'This is where the work really comes in. This method allows us to convert the sid
'into a usable string that LDAP can use to search for the groups this user belongs to.
Public Overloads Shared Function ConvertToOctetString(ByVal values As Byte(), _
     ByVal isAddBackslash As Boolean, ByVal isUpperCase As Boolean) As String
    Dim iterator As Integer
    Dim builder As System.Text.StringBuilder

    Dim slash As String
    If isAddBackslash Then
        slash = "\"
    Else
        slash = String.Empty
    End If
    Dim formatCode As String
    If isUpperCase Then
        formatCode = "X2"
    Else
        formatCode = "x2"
    End If
    builder = New System.Text.StringBuilder(values.Length * 2)
    For iterator = 0 To values.Length - 1
        builder.Append(slash)
        builder.Append(values(iterator).ToString(formatCode))
    Next

    Return builder.ToString()

End Function

TRY THIS
C_A P replied to suresh G on 22-Jan-09 02:31 AM

http://windowsitpro.com/article/articleid/81301/jsi-tip-8240-what-active-directory-groups-exist-that-are-not-enumerated-by-the-net-group-domain-command.html

 

http://www.mssqltips.com/tip.asp?tip=1657