C# 查询一个进程是否有管理员权限

发布时间 2023-12-10 11:45:54作者: log9527
        var hasElevated = false;
        var processName = Process.GetCurrentProcess().ProcessName;
        Process[] processes = Process.GetProcessesByName(processName);
        foreach (var process in processes)
        {
            Console.WriteLine($"进程名称: {process.ProcessName}");
            hasElevated = ProcessHasElevatedPrivileges(process);
            Console.WriteLine($"特权: {hasElevated}");
            if (hasElevated) break;
        }

static bool ProcessHasElevatedPrivileges(Process process)
{
    if (Environment.OSVersion.Version.Major >= 6)
    {
        IntPtr hObject = process.Handle;
        return IsProcessElevated(hObject);
    }
    return false;
}

static bool IsProcessElevated(IntPtr hProcess)
{
    if (!NativeMethods.OpenProcessToken(hProcess, 0x20 | 0x0008, out IntPtr hToken))
    {
        throw new System.ComponentModel.Win32Exception();
    }

    var elevation = default(NativeMethods.TOKEN_ELEVATION);  // 初始化 elevation
    try
    {
        if (!NativeMethods.GetTokenInformation(hToken, NativeMethods.TOKEN_INFORMATION_CLASS.TokenElevation, ref elevation, Marshal.SizeOf(typeof(NativeMethods.TOKEN_ELEVATION)), out var returnLength))
        {
            throw new System.ComponentModel.Win32Exception();
        }

        return elevation.TokenIsElevated != 0;
    }
    finally
    {
        NativeMethods.CloseHandle(hToken);
    }
}

internal static class NativeMethods
{
    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool CloseHandle(IntPtr hObject);

    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern bool OpenProcessToken(IntPtr processHandle, uint desiredAccess, out IntPtr tokenHandle);

    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool GetTokenInformation(IntPtr tokenHandle, TOKEN_INFORMATION_CLASS tokenInformationClass, ref TOKEN_ELEVATION TokenInformation, int tokenInformationLength, out int returnLength);

    public enum TOKEN_INFORMATION_CLASS
    {
        TokenElevation = 20,
        TokenElevationType
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct TOKEN_ELEVATION
    {
        public int TokenIsElevated;
    }
}