傳統方式:
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;}}