tags:

views:

3050

answers:

2

I read a list of SID from the registry, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList.

How to resolve the display username (e.g. DOMAIN\user, BUILDIN\user) by a given SID string in C#?

+1  A: 

The Win32 API function LookupAccountSid() is used to find the name that corresponds to a SID.

LookupAccountSid() has the following signature:

BOOL LookupAccountSid(LPCTSTR lpSystemName, PSID Sid,LPTSTR Name, LPDWORD cbName,
                       LPTSTR ReferencedDomainName, LPDWORD cbReferencedDomainName,
                       PSID_NAME_USE peUse);

MSDN Ref.

Here's the P/Invoke reference (with sample code): http://www.pinvoke.net/default.aspx/advapi32.LookupAccountSid

Mitch Wheat
Is there any other way to do it without using p/invoke in C#?
Dennis Cheung
No, not that I know of.
Mitch Wheat
+6  A: 

Just found it on the pinvoke.net.

Alternative Managed API: Available in .Net 2.0:

using System.Security.Principal;

// convert the user sid to a domain\name
string account = new SecurityIdentifier(stringSid).Translate(typeof(NTAccount)).ToString();
Dennis Cheung
This solution is not reliable in all situations. There are sometimes SIDs which cannot be translated and this will throw an exception. I've found LookupAccountSid() to be more reliable.
BrianLy