一旦我的程序安装在客户端机器上,我如何强制我的程序在Windows 7上以管理员身份运行?


当前回答

这不会强制应用程序以管理员身份工作。 这是这个答案的简化版本,上面的@NG

public bool IsUserAdministrator()
{
    try
    {
        WindowsIdentity user = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(user);
        return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch
    {
        return false;
    }
}

其他回答

如果出于某种原因需要纯代码解决方案,这里有一个独立的类文件。只需在应用程序启动时调用“AdminRelauncher.RelaunchIfNotAdmin()”:

using System;
using System.Diagnostics;
using System.Reflection;
using System.Security.Principal;

public static class AdminRelauncher
{
    public static void RelaunchIfNotAdmin()
    {
        if (!RunningAsAdmin())
        {
            Console.WriteLine("Running as admin required!");
            ProcessStartInfo proc = new ProcessStartInfo();
            proc.UseShellExecute = true;
            proc.WorkingDirectory = Environment.CurrentDirectory;
            proc.FileName = Assembly.GetEntryAssembly().CodeBase;
            proc.Verb = "runas";
            try
            {
                Process.Start(proc);
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine("This program must be run as an administrator! \n\n" + ex.ToString());
                Environment.Exit(0);
            }
        }
    }

    private static bool RunningAsAdmin() 
    {
        WindowsIdentity id = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(id);

        return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
}

这不会强制应用程序以管理员身份工作。 这是这个答案的简化版本,上面的@NG

public bool IsUserAdministrator()
{
    try
    {
        WindowsIdentity user = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(user);
        return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch
    {
        return false;
    }
}

您可以使用ClickOnce Security Settings创建清单,然后禁用它:

Right click on the Project -> Properties -> Security -> Enable ClickOnce Security Settings

单击后,将在项目的属性文件夹下创建一个名为app.manifest的文件,一旦创建,您可以取消选中启用ClickOnce安全设置选项

打开该文件并更改这一行:

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

to:

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

这将使程序需要管理员权限。

另一种方法是仅在代码中检测进程是否以admin身份运行,就像@NG..然后再次打开应用程序并关闭当前应用程序。

当应用程序仅在某些条件下运行时需要管理权限时,例如将其自身作为服务安装时,我使用此代码。所以它不需要像其他答案一样一直以管理员身份运行。

注意,在下面的代码中,NeedsToRunAsAdmin是一个检测当前条件下是否需要管理权限的方法。如果返回false,代码将不会提升自身。这是这种方法相对于其他方法的主要优势。

尽管这段代码具有上述优点,但它确实需要作为一个新进程重新启动自己,这并不总是您想要的。

private static void Main(string[] args)
{
    if (NeedsToRunAsAdmin() && !IsRunAsAdmin())
    {
        ProcessStartInfo proc = new ProcessStartInfo();
        proc.UseShellExecute = true;
        proc.WorkingDirectory = Environment.CurrentDirectory;
        proc.FileName = Assembly.GetEntryAssembly().CodeBase;

        foreach (string arg in args)
        {
            proc.Arguments += String.Format("\"{0}\" ", arg);
        }

        proc.Verb = "runas";

        try
        {
            Process.Start(proc);
        }
        catch
        {
            Console.WriteLine("This application requires elevated credentials in order to operate correctly!");
        }
    }
    else
    {
        //Normal program logic...
    }
}

private static bool IsRunAsAdmin()
{
    WindowsIdentity id = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(id);

    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}

添加一个requestedExecutionLevel元素到你的清单中只是战斗的一半;你必须记住UAC是可以关闭的。如果是,你必须执行老式的检查方法,如果用户不是管理员(在你的线程的CurrentPrincipal上调用IsInRole(WindowsBuiltInRole.Administrator)),就弹出一个错误对话框。