传统方式:
WindowsPrincipal winPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool admin = winPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
这种方式虽然是最常用的检测管理员权限的方法,但是有个致命的缺陷,就是在应用程序为非管理员权限下的时候,获取的值为false,但其实当前user是管理员权限。
所以在这种情况下,需要以下面的方式获取稍为靠谱:
static string ExecuteWithErrorHandling(string command){try{Process process = new Process{StartInfo = {FileName = "cmd.exe",Arguments = "/c " + command,RedirectStandardOutput = true,UseShellExecute = false,CreateNoWindow = true}};process.Start();string output = process.StandardOutput.ReadToEnd();process.WaitForExit();return output;}catch (Exception ex){return $"执行异常:{ex.Message}";}}static bool IsAdministratorByCurUser(){try{var identity = WindowsIdentity.GetCurrent();var executeRes = ExecuteWithErrorHandling($"net localgroup administrators | findstr \"{identity.Name}\"");return !string.IsNullOrWhiteSpace(executeRes) && executeRes.Contains(identity.Name);}catch{return false;}}