現在の 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 ベースのアプローチよりもはるかに高速です。
ただし、最後に気になることが 1 つあります。管理者グループの SecurityIdentifier を名前に変換する必要があります。SID を使用して DirectoryEntry を直接取得する方法が必要です。Googleによると、これはうまくいくはずです:
string path = "LDAP://<SID=" + adminIdentifier.ToString() + ">";
ただし、これは機能しないようです。構文がどのように見えるべきか考えていますか?