如何强制我的。net应用程序以管理员身份运行?

时间:2022-06-02 20:35:18

Once my program is installed on a client machine, how do I force my program to run as an administrator on Windows 7?

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

11 个解决方案

#1


923  

You'll want to modify the manifest that gets embedded in the program. This works on Visual Studio 2008 and higher: Project + Add New Item, select "Application Manifest File". Change the <requestedExecutionLevel> element to:

您将希望修改嵌入到程序中的清单。这是在Visual Studio 2008和更高版本:Project +添加新项目,选择“应用程序清单文件”。将 元素改为:

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

The user gets the UAC prompt when they start the program. Use wisely; their patience can wear out quickly.

用户在启动程序时获得UAC提示。明智地使用;他们的耐心很快就会耗尽。

#2


130  

Adding a requestedExecutionLevel element to your manifest is only half the battle; you have to remember that UAC can be turned off. If it is, you have to perform the check the old school way and put up an error dialog if the user is not administrator
(call IsInRole(WindowsBuiltInRole.Administrator) on your thread's CurrentPrincipal).

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

#3


45  

I implemented some code to do it manually:

我实现了一些手动操作的代码:

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

#4


39  

You can embed a manifest file in the EXE file, which will cause Windows (7 or higher) to always run the program as an administrator.

您可以在EXE文件中嵌入一个清单文件,这将导致Windows(7或更高)始终以管理员的身份运行程序。

You can find more details in Step 6: Create and Embed an Application Manifest (UAC) (MSDN).

您可以在步骤6中找到更多的细节:创建并嵌入一个应用程序清单(UAC) (MSDN)。

#5


30  

The detailed steps are as follow.

具体步骤如下。

  1. Add application manifest file to solution
  2. 将应用程序清单文件添加到解决方案中。
  3. Change application setting to "app.manifest"
  4. 将应用程序设置更改为“app.manifest”
  5. Update tag of "requestedExecutionLevel" to requireAdministrator.
  6. 更新“requestedExecutionLevel”的标签,以满足需求。

如何强制我的。net应用程序以管理员身份运行?

如何强制我的。net应用程序以管理员身份运行?

如何强制我的。net应用程序以管理员身份运行?

如何强制我的。net应用程序以管理员身份运行?

Note that using this code you need to turn off the security settings of ClickOnce, for do this, go inside Properties -> Security -> ClickOnce Security

注意,使用此代码,您需要关闭ClickOnce的安全设置,因为这样做,进入属性->安全-> ClickOnce安全。

#6


14  

While working on Visual Studio 2008, right click on Project -> Add New Item and then chose Application Manifest File.

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

In the manifest file, you will find the tag requestedExecutionLevel, and you may set the level to three values:

在清单文件中,您将找到标记requestedExecutionLevel,您可以将级别设置为三个值:

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

< requestedExecutionLevel水平= " asInvoker“uiAccess = " false " / >

OR

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

< requestedExecutionLevel水平= " requireAdministrator“uiAccess = " false " / >

OR

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

< requestedExecutionLevel水平= " highestAvailable“uiAccess = " false " / >

To set your application to run as administrator, you have to chose the middle one.

要将您的应用程序设置为管理员,您必须选择中间的。

#7


10  

In Visual Studio 2010 right click your project name. Hit "View Windows Settings", this generates and opens a file called "app.manifest". Within this file replace "asInvoker" with "requireAdministrator" as explained in the commented sections within the file.

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

#8


10  

As per

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

you will want to add an application manifest if you don't already have one or don't know how to add one. As some projects don't automatically add a separate manifest file, first go to project properties, navigate to the Application tab and check to make sure your project is not excluding the manifest at the bottom of the tap.

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

  • Next, right click project
  • 接下来,右键单击项目
  • Add new Item
  • 添加新项
  • Last, find and click Application Manifest File
  • 最后,查找并单击应用程序清单文件。

#9


3  

Another way of doing this, in code only, is to detect if the process is running as admin like in the answer by @NG.. And then open the application again and close the current one.

另一种方法是,仅在代码中,通过@NG来检测进程是否以admin的形式运行。然后再次打开应用程序,关闭当前应用程序。

I use this code when an application only needs admin privileges when run under certain conditions, such as when installing itself as a service. So it doesn't need to run as admin all the time like the other answers force it too.

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

Note in the below code NeedsToRunAsAdmin is a method that detects if under current conditions admin privileges are required. If this returns false the code will not elevate itself. This is a major advantage of this approach over the others.

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

Although this code has the advantages stated above, it does need to re-launch itself as a new process which isn't always what you want.

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

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

#10


1  

You can create the manifest using ClickOnce Security Settings, and then disable it:

您可以使用ClickOnce安全设置创建清单,然后禁用它:

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

After you clicked it, a file will be created under the Project's properties folder called app.manifest once this is created, you can uncheck the Enable ClickOnce Security Settings option

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

Open that file and change this line :

打开文件并更改这一行:

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

to:

:

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

This will make the program require administrator privileges.

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

#11


-3  

Right click your executable, go to Properties > Compatibility and check the 'Run this program as admin' box.

右击可执行文件,转到属性>兼容性,并检查“运行此程序作为管理”框。

If you want to run it as admin for all users, do the same thing in 'change setting for all users'.

如果你想为所有用户运行它,那么在“为所有用户更改设置”中也要做同样的事情。

#1


923  

You'll want to modify the manifest that gets embedded in the program. This works on Visual Studio 2008 and higher: Project + Add New Item, select "Application Manifest File". Change the <requestedExecutionLevel> element to:

您将希望修改嵌入到程序中的清单。这是在Visual Studio 2008和更高版本:Project +添加新项目,选择“应用程序清单文件”。将 元素改为:

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

The user gets the UAC prompt when they start the program. Use wisely; their patience can wear out quickly.

用户在启动程序时获得UAC提示。明智地使用;他们的耐心很快就会耗尽。

#2


130  

Adding a requestedExecutionLevel element to your manifest is only half the battle; you have to remember that UAC can be turned off. If it is, you have to perform the check the old school way and put up an error dialog if the user is not administrator
(call IsInRole(WindowsBuiltInRole.Administrator) on your thread's CurrentPrincipal).

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

#3


45  

I implemented some code to do it manually:

我实现了一些手动操作的代码:

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

#4


39  

You can embed a manifest file in the EXE file, which will cause Windows (7 or higher) to always run the program as an administrator.

您可以在EXE文件中嵌入一个清单文件,这将导致Windows(7或更高)始终以管理员的身份运行程序。

You can find more details in Step 6: Create and Embed an Application Manifest (UAC) (MSDN).

您可以在步骤6中找到更多的细节:创建并嵌入一个应用程序清单(UAC) (MSDN)。

#5


30  

The detailed steps are as follow.

具体步骤如下。

  1. Add application manifest file to solution
  2. 将应用程序清单文件添加到解决方案中。
  3. Change application setting to "app.manifest"
  4. 将应用程序设置更改为“app.manifest”
  5. Update tag of "requestedExecutionLevel" to requireAdministrator.
  6. 更新“requestedExecutionLevel”的标签,以满足需求。

如何强制我的。net应用程序以管理员身份运行?

如何强制我的。net应用程序以管理员身份运行?

如何强制我的。net应用程序以管理员身份运行?

如何强制我的。net应用程序以管理员身份运行?

Note that using this code you need to turn off the security settings of ClickOnce, for do this, go inside Properties -> Security -> ClickOnce Security

注意,使用此代码,您需要关闭ClickOnce的安全设置,因为这样做,进入属性->安全-> ClickOnce安全。

#6


14  

While working on Visual Studio 2008, right click on Project -> Add New Item and then chose Application Manifest File.

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

In the manifest file, you will find the tag requestedExecutionLevel, and you may set the level to three values:

在清单文件中,您将找到标记requestedExecutionLevel,您可以将级别设置为三个值:

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

< requestedExecutionLevel水平= " asInvoker“uiAccess = " false " / >

OR

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

< requestedExecutionLevel水平= " requireAdministrator“uiAccess = " false " / >

OR

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

< requestedExecutionLevel水平= " highestAvailable“uiAccess = " false " / >

To set your application to run as administrator, you have to chose the middle one.

要将您的应用程序设置为管理员,您必须选择中间的。

#7


10  

In Visual Studio 2010 right click your project name. Hit "View Windows Settings", this generates and opens a file called "app.manifest". Within this file replace "asInvoker" with "requireAdministrator" as explained in the commented sections within the file.

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

#8


10  

As per

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

you will want to add an application manifest if you don't already have one or don't know how to add one. As some projects don't automatically add a separate manifest file, first go to project properties, navigate to the Application tab and check to make sure your project is not excluding the manifest at the bottom of the tap.

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

  • Next, right click project
  • 接下来,右键单击项目
  • Add new Item
  • 添加新项
  • Last, find and click Application Manifest File
  • 最后,查找并单击应用程序清单文件。

#9


3  

Another way of doing this, in code only, is to detect if the process is running as admin like in the answer by @NG.. And then open the application again and close the current one.

另一种方法是,仅在代码中,通过@NG来检测进程是否以admin的形式运行。然后再次打开应用程序,关闭当前应用程序。

I use this code when an application only needs admin privileges when run under certain conditions, such as when installing itself as a service. So it doesn't need to run as admin all the time like the other answers force it too.

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

Note in the below code NeedsToRunAsAdmin is a method that detects if under current conditions admin privileges are required. If this returns false the code will not elevate itself. This is a major advantage of this approach over the others.

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

Although this code has the advantages stated above, it does need to re-launch itself as a new process which isn't always what you want.

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

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

#10


1  

You can create the manifest using ClickOnce Security Settings, and then disable it:

您可以使用ClickOnce安全设置创建清单,然后禁用它:

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

After you clicked it, a file will be created under the Project's properties folder called app.manifest once this is created, you can uncheck the Enable ClickOnce Security Settings option

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

Open that file and change this line :

打开文件并更改这一行:

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

to:

:

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

This will make the program require administrator privileges.

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

#11


-3  

Right click your executable, go to Properties > Compatibility and check the 'Run this program as admin' box.

右击可执行文件,转到属性>兼容性,并检查“运行此程序作为管理”框。

If you want to run it as admin for all users, do the same thing in 'change setting for all users'.

如果你想为所有用户运行它,那么在“为所有用户更改设置”中也要做同样的事情。