通过SID解析显示用户名的最佳方法是什么?
问题描述:
我从注册表中读取SID列表HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
。通过SID解析显示用户名的最佳方法是什么?
如何解决显示用户名(例如DOMAIN\user
,BUILT-IN\user
)给定SID字符串在C#中?
答
Win32 API函数LookupAccountSid()
用于查找与SID对应的名称。
LookupAccountSid()
具有以下特征:
BOOL LookupAccountSid(LPCTSTR lpSystemName, PSID Sid,LPTSTR Name, LPDWORD cbName,
LPTSTR ReferencedDomainName, LPDWORD cbReferencedDomainName,
PSID_NAME_USE peUse);
MSDN Ref。
这里的的P/Invoke参考(样本代码):http://www.pinvoke.net/default.aspx/advapi32.LookupAccountSid
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError = true)]
static extern bool LookupAccountSid (
string lpSystemName,
[MarshalAs(UnmanagedType.LPArray)] byte[] Sid,
StringBuilder lpName,
ref uint cchName,
StringBuilder ReferencedDomainName,
ref uint cchReferencedDomainName,
out SID_NAME_USE peUse);
答
刚刚发现它的pinvoke.net。
替代托管API: 可在NET 2.0:
using System.Security.Principal;
// convert the user sid to a domain\name
string account = new SecurityIdentifier(stringSid).Translate(typeof(NTAccount)).ToString();
是否有任何其他方式做到这一点不使用P/Invoke在C#中? – 2008-12-19 03:57:21
@ DennisC你可以做到没有P/Invoke。请参阅我的答案:http://*.com/questions/7593005/convert-sid-to-username-in-c-sharp/7593200 – 2017-03-21 02:10:17