Thanks to a little help I gleaned from https://stackoverflow.com/a/3681442/1222122, I figured out what I was doing wrong. I was setting up the PrincipalContext incorrectly. I didn't need to give it the domain, username, or password, just the ContextType. The following code works for both local machine accounts and domain accounts:
public void ListAllGroupsDomain()
{
ListAllGroups(ContextType.Domain, "myDomainUsername");
}
public void ListAllGroupsMachine()
{
ListAllGroups(ContextType.Machine, "myMachineUsername");
}
public void ListAllGroups(ContextType contextType, string userName)
{
using (var context = new PrincipalContext(contextType))
{
using (var findByIdentity = UserPrincipal.FindByIdentity(context, userName))
{
if (findByIdentity != null)
{
var groups = findByIdentity.GetGroups(context);
var results = groups.Select(g => g.Name).ToArray();
Console.WriteLine("Listing {0} groups", results.Count());
foreach (var name in results)
{
Console.WriteLine("{0}", name);
}
}
}
}
}
The only thing I needed to be sure to do was to strip out the domain from the username before I passed it to ListAllGroups
because the function that was providing it to me would prepend it to the username in some cases.