I have the following method to get all Groups a User belongs to:
public static void GetMembership(string userName)
{
UserPrincipal user = null;
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
{
if ((user = UserPrincipal.FindByIdentity(ctx, userName)) != null)
{
PrincipalSearchResult<Principal> groups = user.GetGroups();
foreach (GroupPrincipal g in groups)
{
MessageBox.Show(userName + " is in Name " + g.Name);
}
}
}
}
My problem is that I sometimes get the errors:
System.FormatException: 'Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'
System.Runtime.InteropServices.COMException: '0x80005000'
But I dont want to get or check the Guid or where did this error come from?
Thank you and best regards
Found a Solution by adding currentDomain to my Principalcontext and in my FindbyIdentity adding 'IdentityType.SamAccountName':
public async Task GetMembership(string userName)
{
UserPrincipal user = null;
String currentDomain = Domain.GetCurrentDomain().ToString();
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, currentDomain);
{
if ((user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userName)) != null)
{
PrincipalSearchResult<Principal> groups = user.GetGroups();
foreach (GroupPrincipal g in groups)
{
MessageBox.Show(userName + " is in Group: " + g.Name + " GUID " + g.Guid + " SID " + g.Sid );
}
}
}
}
User contributions licensed under CC BY-SA 3.0