Carl Carl - 10 months ago 56
C# Question

Determine the LocalSystem account name using C#

We have an application that installs SQL Server Express from the command line and specifies the service account as the LocalSystem account via the parameter SQLACCOUNT="NT AUTHORITY\SYSTEM".

This doesn't work with different languages because the account name for LocalSystem is different. There's a table listing the differences here:

This doesn't seem to be complete (the Swedish version isn't listed). So I'd like to be able to determine the name programmatically, perhaps using the SID?

I've found some VB Script to do this:

Set objWMI = GetObject("winmgmts:root\cimv2")

Set objSid = objWMI.Get("Win32_SID.SID='S-1-5-18'")

MsgBox objSid.ReferencedDomainName & "\" & objSid.AccountName

Does anyone know the equivalent code that can be used in C#?

mdb mdb
Answer Source

You can use .NET's built-in System.Security.Principal.SecurityIdentifier class for this purpose: by translating it into an instance of NtAccount you can obtain the account name:

using System.Security.Principal;

SecurityIdentifier sid = new SecurityIdentifier("S-1-5-18");
NTAccount acct = (NTAccount)sid.Translate(typeof(NTAccount));

Later edit, in response to question in comments: you do not need any special privileges to do SID-to-name lookups on the local machine -- for example, even if the user account you're running under is only in the Guests group, this code should work. Things are a little bit different if the SID resolves to a domain account, but even that should work correctly in most cases, as long as you're logged on to the domain (and a domain controller is available at the time of the lookup).