Standard Data Types
The majority of Active Directory and ADAM attributes have simple conversions to .NET data types, with strings being the most popular. We can generally just cast any data type from the System.Object returned by the collection class back to its corresponding actual runtime type:
//given a DirectoryEntry entry and a SearchResult result //we access the single-valued attribute cn which at runtime //will be a simple string string name = (string) entry.Properties["name"].Value; //or name = (string) result.Properties["name"][0];
In Visual Basic .NET, the preceding code would look something like this:
Dim cn As String cn = DirectCast(entry.Properties("cn").Value, String) cn = DirectCast(result.Properties("cn")(0), String)
Note that we can also use CType in Visual Basic .NET. The only problem is that CType will happily try a coercive conversion if the direct conversion does not work, so we need to be careful. Since DirectCast will not do this, we generally recommend using it when we just want to cast.
The other basic conversions are very similar:
DateTime createDate = (DateTime) entry.Properties["whenCreated"].Value; int userAccountControl = (int) entry.Properties["userAccountControl"].Value; bool isSystemOnly = (bool) entry.Properties["systemOnly"].Value;
As demonstrated, the actual type conversion is straightforward. We will most likely want to check if the value can be null or multivalued before blindly using the Value property or directly accessing the array by index. (We omitted this here.)