【问题标题】:The best way to resolve display username by SID?通过 SID 解析显示用户名的最佳方法?
【发布时间】:2008-12-19 03:32:31
【问题描述】:

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

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

【问题讨论】:

    标签: c# windows sid


    【解决方案1】:

    刚刚在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();
    

    【讨论】:

    • 此解决方案并非在所有情况下都可靠。有时存在无法翻译的 SID,这将引发异常。我发现 LookupAccountSid() 更可靠。
    【解决方案2】:

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

    【讨论】:

    • 在 C# 中不使用 p/invoke 有没有其他方法?
    • @DennisC 你可以在没有 P/Invoke 的情况下做到这一点。请看我的回答:stackoverflow.com/questions/7593005/…
    • @EriawanKusumawardhono 我猜你可能没有很好地阅读这些问题。因为它们是完全相反的 API
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    相关资源
    最近更新 更多