Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to resolve display username by SID?

Tags:

c#

windows

sid

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

How would one resolve the display username (e.g. DOMAIN\user, BUILT-IN\user) given the SID string in C#?

like image 611
Dennis C Avatar asked Dec 19 '08 03:12

Dennis C


2 Answers

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();
like image 56
Dennis C Avatar answered Nov 08 '22 10:11

Dennis C


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

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError = true)]
static extern bool LookupAccountSid (
  string lpSystemName,
  [MarshalAs(UnmanagedType.LPArray)] byte[] Sid,
  StringBuilder lpName,
  ref uint cchName,
  StringBuilder ReferencedDomainName,
  ref uint cchReferencedDomainName,
  out SID_NAME_USE peUse); 
like image 41
Mitch Wheat Avatar answered Nov 08 '22 11:11

Mitch Wheat