I am working with the System.DirectoryServices.AccountManagement namespace’s PrincipalContext class to bind to Active Directory and perform operations against the directory. A problem cropped up recently that took a bit of sleuthing to solve and I want to share the solution in hopes that it will save someone else a bit of a headache.
I received the following errors while trying to use a PrincipalContext I created. Of course I love the seemingly ubiquitous Unknown error from COM when something goes wrong…very helpful!
System.Runtime.InteropServices.COMException occurred in System.DirectoryServices: Unknown error (0x80005000) System.DirectoryServices.AccountManagement.PrincipalOperationException occurred in System.DirectoryServices.AccountManagement: Unknown error (0x80005000)
After quite a bit of research and code tweaking I pinned down the problem and came up with a solution. I am using a PrincipalContext constructor overload that specifies ContextOptions and both these constructors (as of .NET 4.0 at least) require you to specify a string for the container parameter. I used an empty string (String.Empty) and assumed this would bind to the root DSE of the directory.
Well, I assumed wrong (and we all know what ASSUME does!). Using an empty string causes the errors above. To fix the issue, use null for the container parameter value and this should create a valid PrincipalContext without our Unknown error friend.