Max Schmeling
Max Schmeling

Reputation: 12509

Given a user's SID, how do I get their userPrincipalName?

I have a list of user's security identifiers and I need to get a list of userPrincipalName's... is there any way that I can get it without loading up the users DirectoryEntry and pulling in the userPrincipalName property?

I need the most efficient method possible because this is done a lot

Upvotes: 6

Views: 9638

Answers (2)

marc_s
marc_s

Reputation: 754240

If you're on .NET 3.5, check out this excellent MSDN article Managing Directory Security Principals in the .NET Framework 3.5.

It shows the new enhanced search capabilities of .NET 3.5's System.DirectoryServices.AccountManagement namespace.

One nice feature is the FindByIdentity method, which allows you to find a user (or group) based on an identity - whether that's the user principal name, the distinguished name, a GUID or the SID - it'll just work :

UserPrincipal user = 
  UserPrincipal.FindByIdentity(principalContext,
                               IdentityType.Sid, (value));

You need to make sure to provide the SID in the proper format - see the MSDN docs for details.

Once you have the user principal object, just get its user principal name:

if(user != null)
{ 
     string upn = user.UserPrincipalName;
}

The sample code for the article even has two additional helper methods FindByIdentityGuid and FindByIdentitySid to achieve exactly what you're looking for!

Go check it out and use it.

Upvotes: 8

adrianbanks
adrianbanks

Reputation: 82934

You can get this using the LookupAccountSid() method to call out to Win32. There is some sample code on the page I have linked to that shows a simple example.

Upvotes: -1

Related Questions