0

I have the windows console program code below that should show up NT Authoroty\Network Service but surprisingly it spells NetworkService without a space... When I check the account the SQLAgent is running on it's indeed Network Service.

Why does this code delete the space? it breaks all my solution down by doing so as NetworkService does not exist.

PS: I don't want to hard code the user; I must get it automatically.

class Program
{
    static string GetSQLAgentUsername()
    {
        string servicePath = string.Format("Win32_Service.Name='{0}'", "SQLSERVERAGENT");
        using (ManagementObject theService = new ManagementObject(new ManagementPath(servicePath)))
        {
            return theService.Properties["StartName"].Value.ToString();
        }
    }

    static void Main(string[] args)
    {
        System.Console.WriteLine(GetSQLAgentUsername());
        System.Console.ReadKey();
    }


}
CoolStraw
  • 5,282
  • 8
  • 42
  • 64

1 Answers1

2

According to this MSDN page, it is because:

While the security subsystem localizes this account name, the SCM does not support localized names. Therefore, you will receive a localized name for this account from the LookupAccountSid function, but the name of the account must be NT AUTHORITY\NetworkService when you call CreateService or ChangeServiceConfig, regardless of the locale, or unexpected results can occur.

The value that you get when retrieving the name from WMO, you are getting the value that was passed to CreateService (AUTHORITY\NetworkService) verbatim.

I'd be surprised if there was another API that required "AUTHORITY\NETWORK SERVICE" though, can you give an example?

Chris Shain
  • 50,833
  • 6
  • 93
  • 125
  • This code also returns "NT AUTHORITY\NETWORK SERVICE" `SecurityIdentifier ident = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null); string name = ident.Translate(typeof(NTAccount)).Value;` – jessehouwing May 22 '12 at 19:57
  • I am getting this issue mostly because the TFS API uses the localized names. If I query the workspaces for a specific user (in this case our build server's service account), I need to translate the account received from WMI to the account expected by the TFS API. – jessehouwing May 22 '12 at 21:03
  • It looks like you may need to resort to some pinvoking. Perhaps a call to LsaLookupNames (http://msdn.microsoft.com/en-us/library/windows/desktop/ms721797(v=vs.85).aspx) to get the sid, then a call to LsaLookupSids2 (http://msdn.microsoft.com/en-us/library/windows/desktop/hh448528(v=vs.85).aspx) to get the names? I'm not on a windows box right now, but I can give this a try later if you are uncomfortable with the pinvoke code. – Chris Shain May 22 '12 at 21:10