Working with Directory Services in C#

In this article I will explain you about Working with Directory Services in C#.


This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

Microsoft has provided the Active Directory Service Interface (ADSI), an API for directory services, for many years. ADSI allows us to access the directory services of various network providers in a distributed computing environment, and it presents a single set of directory service interfaces for managing network resources. We can list and manage the resources in a directory service via the ADSI service, but we do not need to know where the actual resource is located. We can use ADSI to perform common administrative tasks such as searching resources like computers, users, printers, shares, and groups on an enterprise computer network. 

When you install a Windows 2000 domain controller and are creating a new forest and domain, you install the Active Directory (and optionally an Active Directory-integrated DNS if one does not exist), in which all resource information is stored. The Windows 2000 Active Directory allows you to store information about all kinds of resources such as computers, groups, printers, shares, users, and so on. If you want to surf through an Active Directory, you would use the basic program named LDP.EXE from theWindows2000 support tools, in the Windows 2000 CD's support directory. Active Directory is a database that has a storage structure similar to that of the Registry-namely, hierarchical rather than relational. This statement is also valid for other LDAP (Lightweight Directory Access Protocol ) servers and stores. You can also think of it as an XML Document Object Model tree. Every object inside Active Directory is created based on a schema object type, has an LDAP path relative to the root, and has particular attributes such as name and global unique identifier (GUID). The created objects of valid schema types reside as nodes in the Active Directory tree. 

Figure 21.2 shows a simple model of an Active Directory tree and node. (Note that the same logic applies to all LDAP servers such as Microsoft Internet Information Server.) 

Figure-21.2.gif

Figure 21.2: Active Directory Data and Search Model Root 

The DirectoryEntry class presents a node or object in the Active Directory hierarchy. The Add method creates a request to create a new entry in the container. The Find method returns the child with the specified name. The Remove method deletes a child DirectoryEntry from this collection. Table 21.11 describes the members of the DirectoryEntry class. 

table21.11.gif

Table 21.11: DirectoryEntry Class Members 

The DirectorySearcher class performs queries against the Active Directory. But of the systemsupplied ADSI providers like LDAP, Internet Information Services (IIS), and Novell NetWare Directory Service (NDS), only LDAP supports searching. The Filter property of the DirectorySearcher class gets or sets the LDAP filter string format. The FindAll method in the DirectorySearcher class executes the search and returns a collection of entries found. Table 21.12 describes the members of the DirectorySearcher class. 

table 21.12.gif

Table 21.12: DirectorySearcher Class Members 

You can use Active Directory Users and Computers MMC to manage your Active Directory resources. It resides on the Administrative Tools menu on Windows 2000 servers. 

The code in Listing 21.26 searches the MCBCorp.Com Windows 2000 Active Directory domain. It outputs all of the Active Directory objects and their properties, and then all the data inside, recursively. 

Listing 21.26: Using DirectoryEntry (ldapdir1.cs) 

using System;
using System.DirectoryServices;

class Test
{
    static void Main(string[] args)
    {
        // the name of the domain
        DirectoryEntry entry = new DirectoryEntry(@"LDAP://MCBcorp, DC=com");
        Console.WriteLine("Name = " + entry.Name);
        Console.WriteLine("Path = " + entry.Path);
        Console.WriteLine("SchemaClassName = " + entry.SchemaClassName);
        Console.WriteLine("Properties:");
        Console.WriteLine("=====================================");

        foreach (string key in entry.Properties.PropertyNames)
        {
            try
            {
                Console.WriteLine("\t" + key + " = ");

                foreach (Object objCollection in entry.Properties[key])
                    Console.WriteLine("\t\t" + objCollection);
                Console.WriteLine("===================================");
            }

            catch
            {
            }
        }

        System.DirectoryServices.DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(entry);
        mySearcher.Filter = ("(objectClass=*)");
        Console.WriteLine("Active Directory Information");
        Console.WriteLine("=====================================");

        foreach (System.DirectoryServices.SearchResult resEnt in mySearcher.FindAll())
        {
            try
            {
                Console.WriteLine(resEnt.GetDirectoryEntry().Name.ToString());

                 Console.WriteLine(resEnt.GetDirectoryEntry().Path.ToString());
                Console.WriteLine(
                resEnt.GetDirectoryEntry().NativeGuid.ToString());
                Console.WriteLine("===================================");
            }

            catch
            {
            }
        }
    }
}

You can create entries and properties in the Active Directory. You simply create a new directory or use an existing one with the DirectoryEntry class and then assign the values you want to the specific properties. When you have finished assigning the values, call the CommitChanges() method to cause the changes to occur in the Active Directory. The sample code in Listing 21.27 achieves this update operation. 

Listing 21.27 also shows you how to pick individual properties of Active Directory objects! The properties term of Active Directory is not related to the C# class properties used with get and set. Active Directory properties are an array of adjustable object property members with specific names determined by the Active Directory schema. For example, you can set the following properties for objects: sn, givenName, title, or mycustomproperty. The properties change depending on their class definition in the Active Directory schema. Refer to the Active Directory Schema MMC to discover possible object types and definitions. 

Listing 21.27: Updating Active Directory 

// get the handle to MCBuser from Active Directory database
DirectoryEntry entry = new DirectoryEntry("LDAP://DC=MyDC, O=MyOrg, OU=MyOU, cn=MCBuser");
Entry.Password = "mcb"; // password
(entry.Properties["myprop"] [0] = "myvalue"; // properties
entry.CommitChanges();

Conclusion

Hope this article would have helped you in understanding Working with Directory Services in C#. See other articles on the website on .NET and C#.

visual C-sharp.jpg
The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.