在S#中将SID转换为帐户名称,可以使用以下方法:
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
public static class SIDConverter
{
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool LookupAccountSid(
string lpSystemName,
[MarshalAs(UnmanagedType.LPArray)] byte[] sid,
System.Text.StringBuilder lpName,
ref uint cchName,
System.Text.StringBuilder ReferencedDomainName,
ref uint cchReferencedDomainName,
out SID_NAME_USE peUse);
public static string ConvertSidToAccountName(string sidString)
{
SecurityIdentifier sid = new SecurityIdentifier(sidString);
byte[] sidBytes = new byte[sid.BinaryLength];
sid.GetBinaryForm(sidBytes, 0);
uint cchName = 256;
uint cchReferencedDomainName = 256;
System.Text.StringBuilder name = new System.Text.StringBuilder((int)cchName);
System.Text.StringBuilder domainName = new System.Text.StringBuilder((int)cchReferencedDomainName);
SID_NAME_USE sidType;
if (!LookupAccountSid(null, sidBytes, name, ref cchName, domainName, ref cchReferencedDomainName, out sidType))
{
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
}
return domainName.ToString() + "\\" + name.ToString();
}
}
using System;
using System.Management;
public static class SIDConverter
{
public static string ConvertSidToAccountName(string sidString)
{
string accountName = "";
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher(
"SELECT * FROM Win32_UserAccount WHERE SID = '" + sidString + "'");
foreach (ManagementObject account in searcher.Get())
{
accountName = account["Name"].ToString();
break;
}
}
catch (Exception ex)
{
throw new Exception("Error converting SID to account name: " + ex.Message);
}
return accountName;
}
}
这两种方法都可以将SID转换为帐户名称。其中,第一种方法使用Windows API函数LookupAccountSid(),而第二种方法使用WMI查询。两种方法都可以在C#中使用,但是第一种方法更加通用,可以在不同的编程语言中使用。
领取专属 10元无门槛券
手把手带您无忧上云