.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