我试图弄清楚当前的 Windows 用户是本地管理员还是可以使用 UAC 来“获得”该组成员身份。
到目前为止,我得出的结论是这样的:
var adminIdentifier = new SecurityIdentifier("S-1-5-32-544");
var current = WindowsIdentity.GetCurrent();
bool isAdmin = current.Groups.Contains(adminIdentifier);
bool canBeAdmin = isAdmin;
if (!isAdmin)
{
var adminGroupName = adminIdentifier.Translate(typeof(NTAccount)).Value;
adminGroupName = adminGroupName.Substring(adminGroupName.LastIndexOf('\\'));
string path = "WinNT://./" + adminGroupName + ",group";
using (DirectoryEntry groupEntry = new DirectoryEntry(path))
{
foreach (object member in (IEnumerable)groupEntry.Invoke("Members"))
{
using (DirectoryEntry memberEntry = new DirectoryEntry(member))
{
object obVal = memberEntry.Properties["objectSid"].Value;
SecurityIdentifier sid = null;
if (null != obVal)
{
sid = new SecurityIdentifier((Byte[])obVal,0);
}
canBeAdmin = Equals(current.User, sid);
if (canBeAdmin)
break;
}
}
}
}
Console.WriteLine(canBeAdmin +" "+isAdmin);
此解决方案需要几毫秒的时间来计算。比我之前尝试过的基于 System.DirectoryServices.AccountManagement 的方法快得多。
不过,还有最后一件事困扰着我。我必须将管理员组的 SecurityIdentifier 翻译成名称。应该有办法得到 直接使用 SID 的 DirectoryEntry。据谷歌称,这应该有效:
string path = "LDAP://<SID=" + adminIdentifier.ToString() + ">";
但是,这似乎行不通。知道语法应该是什么样子吗?
最佳答案
你试过了吗WindowsPrincipal.IsInRole ?
WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
wp.IsInRole(new SecurityIdentifier("S-1-5-32-544"));
wp.IsInRole(WindowsBuiltInRole.Administrator);
关于.net - 快速获取群组成员资格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/716951/