Brent Gardner's Blog

It's all about the code.

Syndication

Tags

    No tags have been created or used yet.

Navigation

.NET Sid2User and User2Sid

Every once in a while, I have to resolve a SID (Windows Security IDentifier) to its corresponding user. Throughout the years I've had to do this with the LookupAccountName API call, be it through C++, VB 6, etc. I was doing it that way in .NET, until Steve Schofield altered me to a post on forums.iis.net this morning. A bit of sample code from that site made me realize there was a much easier way to do Sid2User and User2Sid resolution in .NET:

Public Shared Function SidToUser(ByVal Sid As String) As String

    Dim Si As New SecurityIdentifier(SID)

    Dim Nta As NTAccount = CType(Si.Translate(GetType(NTAccount)), NTAccount)

    Return Nta.Value

End Function

Public Shared Function UserToSid(ByVal Username As String) As String

    Dim Terms() As String = Split(Username, "\")

    If Terms.Length > 1 Then Return UserToSid(Terms(0), Terms(1))

    Return UserToSid("", Username)

End Function

Public Shared Function UserToSid(ByVal DomainName As String, ByVal Username As String) As String

    Dim Nta As New NTAccount(DomainName, Username)

    Dim Si As SecurityIdentifier = CType(Nta.Translate(GetType(SecurityIdentifier)), SecurityIdentifier)

    Return Si.Value

End Function

 

Cheers,

- Brent

Published Friday, April 20, 2007 3:22 PM by Brent

Comments

# re: .NET Sid2User and User2Sid @ Monday, June 11, 2007 6:07 PM

Thanks man!  There arent many examples for those classes on MSDN.  This really helped.

TJ

# re: .NET Sid2User and User2Sid @ Thursday, June 14, 2007 4:07 PM

Awesome code. Thanks a bunch.

Benjamin Baxter

Anonymous comments are disabled