Search code examples
c#windowssid

Converting username to SID in C#


I'm trying to use this code to convert a Windows username (in the classic .\username form) to a SID object:

NTAccount account = new NTAccount(".\\MyUser");
SecurityIdentifier sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));

However, I keep getting the following exception when executing the last instruction:

System.Security.Principal.IdentityNotMappedException: 'Some or all identity references could not be translated.'

What am I doing wrong?


Solution

  • Answering my own question after some trial and error:

    The code is correct, but the Translate function doesn't seem to support the shorthand . to indicate the account is local and not in a domain. So in case you have a username that starts with .\ you need to replace the dot with the machine name. The following code works correctly:

    public static SecurityIdentifier usernameToSid(string user)
    {
        if (user.StartsWith(@".\"))
        {
            user = user.Replace(@".\", Environment.MachineName + @"\");
        }
    
        NTAccount account = new NTAccount(user);
        return (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
    }