如果未在管理模式下运行,如何阻止我的程序运行?XP和Windows 7

CRE*_*REW 3 c# security admin

我有一个C#程序,应该是多操作系统兼容的.它需要访问权限才能创建目录并获取WMI数据,但只有在以管理员身份运行程序时才可以使用.否则,它失败了.

如果它没有检测到自己是以管理员身份运行的话,是否有任何命令可用于不运行程序?我尝试添加app.manifest并使用"requireAdministrator",它会提示登录,但这似乎只适用于Windows 7和Vista,而不是XP.

例:

 if (isAdmin==0)
 Console.WriteLine("Please run this as an administrator");
 exit;
Run Code Online (Sandbox Code Playgroud)

MyK*_*SKI 5

检查用户是否为管理员

public static bool IsAdministrator()
{
    WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
    WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity);

    return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
}
Run Code Online (Sandbox Code Playgroud)

如果不是管理员,请重新启动应用

public static bool RestartAsAdministrator(string filePath, string fileName, string errorCaption)
{
    Process process = null;
    ProcessStartInfo processStartInfo = new ProcessStartInfo();
    processStartInfo.FileName = Path.Combine(filePath, fileName);

    if (Environment.OSVersion.Version.Major >= 5) //5 is XP and 6 is Vista and 7
        processStartInfo.Verb = "runas";

    processStartInfo.Arguments = "";
    processStartInfo.WindowStyle = ProcessWindowStyle.Normal;
    processStartInfo.UseShellExecute = true;

    try
    {
        process = Process.Start(processStartInfo);
    }

    catch (Exception)
    {
        MessageBox.Show("Couldn't start as admin.\nPlease try manually by Right Clicking on " + Path.GetFileNameWithoutExtension(fileName) + " and selecting \"Run as administrator\"",
                            errorCaption + " Error", MessageBoxButton.OK, MessageBoxImage.Error);

        return false;
    }

    finally
    {
        if (process != null)
            process.Dispose();
    }

    return true;
}
Run Code Online (Sandbox Code Playgroud)

应用程序清单文件(用于自动运行为管理员)

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
Run Code Online (Sandbox Code Playgroud)