While working on some of our upcoming enterprise features over at Member.buzz, I ran into an issue that wasn't very well documented.
Using the excellent System.DirectoryServices namespace we are able to manage the domain suffixes added to Active Directory.
First, this is how you can retrieve the current suffixes:
List Result = new List();
DirectoryEntry Partition = new DirectoryEntry(@"LDAP://CN=Partitions," + (new DirectoryEntry(@"LDAP://RootDSE").Properties["configurationNamingContext"].Value.ToString()));
var SuffixCollection = Partition.Properties["uPNSuffixes"];foreach (var Suffix in SuffixCollection)
{
Result.Add(Suffix.ToString());
}
Next, we add a new suffix:
var SuffixToAdd = "domain.com";
DirectoryEntry Partition = new DirectoryEntry(@"LDAP://CN=Partitions," + (new DirectoryEntry(@"LDAP://RootDSE").Properties["configurationNamingContext"].Value.ToString()));Partition.Properties["uPNSuffixes"].Add(SuffixToAdd);
Partition.CommitChanges();
Finally, removing a suffix is a little bit tricky. While there is a Remove method in the Properties object, removing a value doesn't seem to persist correctly. Instead, we create a new array, copy the appopriate values and override the existing value.
var SuffixToRemove = "domain.com";
DirectoryEntry Partition = new DirectoryEntry(@"LDAP://CN=Partitions," + (new DirectoryEntry(@"LDAP://RootDSE").Properties["configurationNamingContext"].Value.ToString()));
var Suffixes = Partition.Properties["uPNSuffixes"];
var SuffixList = new List();
var SuffixCollection = Partition.Properties["uPNSuffixes"];
foreach (var Suffix in SuffixCollection)
{
if (Suffix.ToString() == SuffixToRemove) { continue; }
SuffixList.Add(Suffix.ToString());
}
Partition.Properties["uPNSuffixes"].Value = SuffixList.ToArray();Partition.CommitChanges();
And there you have it!