Search code examples
c#.netdirectoryservices

UserPrincipal SamAccountName throws DirectoryServicesCOMException unhandled "A local error has occured"


I'm writing a piece of code that is supposed to search the active directory for a specific users GivenName (forename) and Surname based upon their SamAccountName as the search parameter, and then return a string containing their given name and surname.

The code I have written so far is as follows:

public static string GetName(string uName)
    {
        StringBuilder builder = new StringBuilder();
        using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "serverName"))
        {
            UserPrincipal user = new UserPrincipal(context);

            user.SamAccountName = uName;

            PrincipalSearcher srch = new PrincipalSearcher(user);
            srch.QueryFilter = user;
            PrincipalSearchResult<Principal> res = srch.FindAll();
            foreach (UserPrincipal u in res)
            {
                builder.Append(u.GivenName);
                builder.Append(" ");
                builder.Append(u.Surname);
            }
            return builder.ToString();
        }
    }

The problem I'm having with the above code is that during run-time the line

user.SamAccountName = uName;

throws the following error: DirectoryServicesCOMException unhandled "A local error has occured"

The principal context object is created just fine, as is the user principal object, it only throws the error when executing the line mentioned above. What's even more bizarre is that this code seemed to work a couple of days ago. If anyone reading this has any ideas as to why I'm getting this error I'd be greatly appreciative!

P.S. I resorted to asking about this as the bloody error message is a bit too cryptic to actually figure out, or at least for me anyway (a local error occured) really? Whichever developer thought that was a useful error message is an idiot.


Solution

  • Possible causes:

    1. There is an issue with the computer's domain membership or authentication. For example, is the clock on the computer running the code synchronized (within 5 minutes) of the DCs in the target domain?
    2. The user name is invalid. For example, it contains invalid characters.