0

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?

Master_T
  • 7,232
  • 11
  • 72
  • 144
  • Your parameter account is probably wrong. `NTAccount` constructor doesn't actually check if it is valid: https://referencesource.microsoft.com/#mscorlib/system/security/principal/ntaccount.cs,73 – sibel1us Oct 23 '18 at 08:56
  • How about reading the duplicate and [edit]ing your question to explain why it doesn't apply? The point is that `Translate()` from username to SID or vice versa works for Active Directory accounts, not for local accounts. It doesn't matter in which direction you want to translate. – CodeCaster Oct 23 '18 at 08:58
  • @CodeCaster: actually it works, it just doesn't support the "." shorthand that indicates the local (machine) domain. Replacing the dot with the machine name solved the issue. See the edit in my answer (can't answer properly since you closed the question :| ) – Master_T Oct 23 '18 at 09:14
  • @sibel1us: thanks for the tip, the name was correct but apparently using the "." as a shorthand for the local domain is not supported, you need to use the full machine name, see my edit in the question. Thanks for pointing me in the right direction. – Master_T Oct 23 '18 at 09:16

1 Answers1

0

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));
}
Master_T
  • 7,232
  • 11
  • 72
  • 144