Search code examples
c#.netprincipalcontext

User Principal is always null


I am logged in under user User001 under domain DomainA and with password Pass001.

I use this code

//var principalContext = new PrincipalContext(
    //ContextType.Domain,
    //"DomainA",
    //"User001",
    //"Pass001");

var principalContext = new PrincipalContext(
    ContextType.Domain,
domain, 
    userName,
    password);
var userPrincipal = new UserPrincipal(principalContext);

And userPrincipal is always NULL.

How to fix it?


Solution

  • Somehow this code I found is working fine...

     using (var context = new PrincipalContext(ContextType.Domain))
                {
                    using (UserPrincipal principal = UserPrincipal.FindByIdentity(context, userName))
                    {
                        var uGroups = principal.GetGroups();
                        foreach (var group in uGroups)
                        {
                            Debug.WriteLine(group.DisplayName);
                        }
                    }
                }