C# 通过 SID 解析显示用户名的最佳方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/380031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 01:16:56  来源:igfitidea点击:

The best way to resolve display username by SID?

c#windowssid

提问by Dennis C

I read a list of SIDs from the registry, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList.

我从注册表中读取了 SID 列表,HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList.

How would one resolve the display username (e.g. DOMAIN\user, BUILT-IN\user) given the SID string in C#?

给定 C# 中的 SID 字符串,如何解析显示用户名(例如DOMAIN\userBUILT-IN\user)?

采纳答案by Mitch Wheat

The Win32 API function LookupAccountSid()is used to find the name that corresponds to a SID.

Win32 API 函数LookupAccountSid()用于查找与 SID 对应的名称。

LookupAccountSid()has the following signature:

LookupAccountSid()具有以下签名:

BOOL LookupAccountSid(LPCTSTR lpSystemName, PSID Sid,LPTSTR Name, LPDWORD cbName,
                       LPTSTR ReferencedDomainName, LPDWORD cbReferencedDomainName,
                       PSID_NAME_USE peUse);

MSDN Ref.

MSDN参考

Here's the P/Invoke reference (with sample code): http://www.pinvoke.net/default.aspx/advapi32.LookupAccountSid

这是 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); 

回答by Dennis C

Just found it on the pinvoke.net.

刚刚在pinvoke.net上找到它。

Alternative Managed API: Available in .Net 2.0:

替代托管 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();