我正在尝试查找我识别的用户是否是本地Administrators组的成员。
但我的代码什么也没做......
请参阅下面的代码。
此外,这是在public void Form1_Load(object sender, EventArgs e) {}
中执行的,因此每次应用程序启动时都会执行此操作。
string localUser = WindowsIdentity.GetCurrent().Name.ToString();
char[] trimmingsEnd = { 'a', 'd', 'm', 'i', 'n' };
string trimmedlocalEnd = localUser.TrimEnd(trimmingsEnd);
char[] trimmingsFront = { 'C', 'o', 'm', 'p', 'u', 't', 'e', 'r', '\\' };
string trimmedlocalUser = trimmedlocalEnd.TrimStart(trimmingsFront);
WindowsIdentity windowsIdentity = new WindowsIdentity(trimmedlocalUser);
WindowsPrincipal principal = new WindowsPrincipal(windowsIdentity);
bool IsAdmin = principal.IsInRole("BUILTIN\\" + "Administrators");
if (IsAdmin == false)
MessageBox.Show("not part of admin");
if (IsAdmin == true)
MessageBox.Show("part of admin");
答案 0 :(得分:0)
如果程序正在编译而没有任何问题,那么可能是没有为Form1_Load()设置事件处理程序。
您可能需要添加Form1.Designer.cs文件,如:
this.Load += new System.EventHandler(Form1_Load);
如果有帮助,请告诉我。
答案 1 :(得分:0)
所以,我放弃了上面的方法,因为我能找到的只是当前用户...但我需要在本地管理员组中搜索两个用户名。
以下代码完美地满足了我的需求! 希望这有助于某人。
//Get all users from the local Administrators group and create list
DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry admGroup = localMachine.Children.Find("administrators", "group");
object members = admGroup.Invoke("members", null);
List<string> userList = new List<string>();
//Get current user
string localUser1 = WindowsIdentity.GetCurrent().Name.ToString();
//Take domain name off
char[] trimmingsFront = { 'D', 'O', 'M', 'A', 'I', 'N', '\\' };
string trimmedlocalFront = localUser1.TrimStart(trimmingsFront);
//Take "admin" off username
char[] trimmingsEnd = { 'a', 'd', 'm', 'i', 'n' };
string trimmedlocalUser = trimmedlocalFront.TrimEnd(trimmingsEnd);
//Add each local Administrator to list
foreach (object groupMember in (IEnumerable)members)
{
DirectoryEntry member = new DirectoryEntry(groupMember);
userList.Add(member.Name);
}
//Check if users are not part of list
if (!(userList.Contains(trimmedlocalFront)))
MessageBox.Show(trimmedlocalFront + " is not a member of the local Administrators group. The drag and drop functionality will not work unless " + trimmedlocalFront + " is a member of the local Administrators group. After " + trimmedlocalFront + " is added, please restart your machine for the changes to take effect.", "Local Administrator Warning", MessageBoxButtons.OK, MessageBoxIcon.Stop);
else if (!(userList.Contains(trimmedlocalUser)))
MessageBox.Show(trimmedlocalUser + " is not a member of the local Administrators group. The drag and drop functionality will not work unless " + trimmedlocalUser + " is a member of the local Administrators group. After " + trimmedlocalUser + " is added, please restart your machine for the changes to take effect.", "Local Administrator Warning", MessageBoxButtons.OK, MessageBoxIcon.Stop);
如果您想检查自己的用户名,请在&#39; if&#39;中执行:
if (!(userList.Contains(whateverusernameyouwanttosearch)))