繁体   English   中英

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

[英]How can I prevent my program from running if it is not ran in Administrative mode? XP and Windows 7

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

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

例:

 if (isAdmin==0)
 Console.WriteLine("Please run this as an administrator");
 exit;

检查用户是否为管理员

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

    return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
}

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

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;
}

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

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

您可以使用此功能检查当前用户(启动您的应用程序)是否具有管理员权限。

using System.Security.Principal;
...
bool IsAnAdministrator ()
{
   WindowsIdentity  identity = WindowsIdentity.GetCurrent();
   WindowsPrincipal principal = new WindowsPrincipal (identity);
   return principal.IsInRole(WindowsBuiltInRole.Administrator);
}

如果您调用此方法并返回false ,则可以显示消息和/或关闭应用程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM