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


当前回答

在Visual Studio 2010中右键单击项目名称。 点击“查看Windows设置”,这会生成并打开一个名为“app.manifest”的文件。 在此文件中,将“asInvoker”替换为“requireAdministrator”,如文件中的注释部分所述。

其他回答

我实现了一些代码来手动完成:

using System.Security.Principal;
public bool IsUserAdministrator()
{
    bool isAdmin;
    try
    {
        WindowsIdentity user = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(user);
        isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch (UnauthorizedAccessException ex)
    {
        isAdmin = false;
    }
    catch (Exception ex)
    {
        isAdmin = false;
    }
    return isAdmin;
}

As的

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

如果您还没有或不知道如何添加应用程序清单,则需要添加应用程序清单。由于一些项目不会自动添加单独的清单文件,首先转到项目属性,导航到应用程序选项卡,并检查以确保您的项目没有排除在底部的清单。

接下来,右击项目 添加新项目 最后,找到并单击应用程序清单文件

在Visual Studio 2008上工作时,右键单击项目->添加新项,然后选择应用程序清单文件。

在清单文件中,你会发现标签requestedExecutionLevel,你可以将级别设置为三个值:

<requestExecutionLevel level=“asInvoker” uiAccess=“false” />

OR

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

OR

<requestExecutionLevel level=“highestAvailable” uiAccess=“false” />

要将应用程序设置为以管理员身份运行,必须选择中间的一个。

这不会强制应用程序以管理员身份工作。 这是这个答案的简化版本,上面的@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" />

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