使用C#确定LocalSystem帐户名 [英] Determine the LocalSystem account name using C#

查看:444
本文介绍了使用C#确定LocalSystem帐户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个命令行安装SQL Server Express和指定服务帐户通过参数SQLACCOUNT =NT AUTHORITY\SYSTEMLocalSystem帐户的应用程序。

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:

http://forums.microsoft.com/MSR/ShowPost.aspx?PostID=685354&SiteID=37

这似乎并不完整(瑞典版本未列出)。 ?所以我希望能够以编程方式确定名称,可能使用的SID

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?

我发现了一些VB脚本这样做:

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



有谁知道,可以在C#中使用的等效代码?

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

推荐答案

您可以使用.NET的内置的 System.Security.Principal.SecurityIdentifier 为此类:由翻译成的 NTACCOUNT 可以获取帐户名称:

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));
Console.WriteLine(acct.Value);



后来编辑,针对在评论的问题:你不需要任何特殊的权限来做SID-在本地机器上对名称查找 - 例如,即使你下运行的用户帐户只在来宾组,此代码应工作。事情有点不同如果SID解析为一个域帐户,但即使在大多数情况下正常工作,只要你登录到域(和域控制器可在查找的时间)

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).

这篇关于使用C#确定LocalSystem帐户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆