我從註冊表中讀取SID列表HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
。通過SID解析顯示用戶名的最佳方法是什麼?
如何解決顯示用戶名(例如DOMAIN\user
,BUILT-IN\user
)給定SID字符串在C#中?
我從註冊表中讀取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://stackoverflow.com/questions/7593005/convert-sid-to-username-in-c-sharp/7593200 – 2017-03-21 02:10:17