[英]How can I retrieve the local Machine SID using C#?
用户ewall的另一个SO帖子有一个纯.NET解决方案,其中包含C#和PowerShell中的示例。 它使用DirectoryEntry和SecurityDescriptor对象。 请参阅: 如何使用WMI检索Windows计算机的SID?
你可以通过pinvoke来实现它,只需从Win32 API获取它。
http://www.pinvoke.net/default.aspx/advapi32.lookupaccountname
也许有一种方法可以在“纯粹的”.NET中获得它。
本地用户帐户SID格式: S-1-5-21-xxxxxxxxx-xxxxxxxxx-xxxxxxxxxx-yyyy
系统特定部分: xxx ... xxx
用户帐户特定部分: yyyy
因此,您只需要从用户帐户SID中删除最后一组数字即可获得系统SID。
如果您的代码是Windows应用程序 ,则可以通过以下方式获取系统SID:
using System.Security.Principal;
string systemSid;
using (WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent())
{
systemSid = windowsIdentity.User.Value.Substring(0, windowsIdentity.User.Value.LastIndexOf('-'));
}
如果您的代码是Web应用程序,则它通常在应用程序池标识的上下文中运行,如果您的代码是Windows服务,则它通常在系统帐户(系统,本地服务,网络服务)的上下文中运行。 这些身份都不是用户帐户。 所以你不能使用上面的代码。 您需要知道用户帐户名称或列出用户帐户。
如果您知道用户帐户名,则可以通过以下方式获取系统SID:
using System.Security.Principal;
NTAccount ntAccount = new NTAccount("MACHINE_NAME\\UserAccountName");
SecurityIdentifier sid = (SecurityIdentifier)ntAccount.Translate(typeof(SecurityIdentifier));
string systemSid = sid.Value.Substring(0, sid.Value.LastIndexOf('-'));
但是您不能假设标准用户的名称如“guest”,因为标准本地用户帐户名称已本地化,因为此标准用户帐户可能已被删除,并且因为在将来的Windows版本中可能会禁止标准用户帐户。
因此,大多数情况下,从Web应用程序或Windows服务,您需要通过WMI列出用户帐户:
// your project must reference System.Management.dll
using System.Management;
SelectQuery selectQuery = new SelectQuery("SELECT * FROM Win32_UserAccount");
ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(selectQuery);
string systemSid;
foreach (ManagementObject managementObject in managementObjectSearcher.Get())
{
if (1 == (byte)managementObject["SIDType"])
{
systemSid = managementObject["SID"] as string;
break;
}
}
systemSid = systemSid.Substring(0, systemSid.Value.LastIndexOf('-'));
Win32_UserAccount类文档:
https://msdn.microsoft.com/en-us/library/aa394507(v=vs.85).aspx
UPDATE
大约快100倍:
using Microsoft.Win32;
RegistryKey key = null;
string sid = null;
try
{
foreach (string subKeyName in Registry.Users.GetSubKeyNames())
{
if(subKeyName.StartsWith("S-1-5-21-"))
{
sid = subKeyName.Substring(0, subKeyName.LastIndexOf('-'));
break;
}
}
}
catch (Exception ex)
{
// ...
}
finally
{
if (key != null)
key.Close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.