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

发布于 2024-12-25 20:34:18 字数 70 浏览 10 评论 0 原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

时光病人 2025-01-01 20:34:18

您需要修改嵌入到程序中的清单。这适用于 Visual Studio 2008 及更高版本:项目 + 添加新项,选择“应用程序清单文件”。将 元素更改为:

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

用户获取 UAC当他们启动程序时提示。明智地使用;他们的耐心很快就会消失。

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:

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

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

画▽骨i 2025-01-01 20:34:18

在清单中添加 requestedExecutionLevel 元素只是成功的一半;您必须记住,UAC 可以关闭。如果是,您必须以旧式方式执行检查,如果用户不是管理员
(调用IsInRole(WindowsBuiltInRole.Administrator) 位于线程的 CurrentPrincipal 上)。

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).

深居我梦 2025-01-01 20:34:18

详细步骤如下。

  1. 将应用程序清单文件添加到项目
  2. 将应用程序设置更改为“app.manifest”
  3. 将“requestedExecutionLevel”标记更新为requireAdministrator。

添加文件于解决方案

选择清单选项

Update Manifest file

请注意,使用此代码您需要关闭 ClickOnce 的安全设置,为此,请转到里面的属性->安全-> ClickOnce 安全

The detailed steps are as follow.

  1. Add application manifest file to project
  2. Change application setting to "app.manifest"
  3. Update tag of "requestedExecutionLevel" to requireAdministrator.

Adding file in Solution

Select Application Manifest File

Select Manifest option

Update Manifest file

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

怀中猫帐中妖 2025-01-01 20:34:18

我实现了一些代码来手动执行此操作:

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

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;
}
我的影子我的梦 2025-01-01 20:34:18

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

您可以在步骤 6:创建并嵌入应用程序清单 ( UAC) (MSDN)。

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.

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

你的他你的她 2025-01-01 20:34:18

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

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

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

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

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

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

OR

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

OR

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

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

心碎无痕… 2025-01-01 20:34:18

另一种方法(仅在代码中)是检测进程是否以管理员身份运行,如 @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);
}

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.

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.

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);
}
猫烠⑼条掵仅有一顆心 2025-01-01 20:34:18

如果您还没有应用

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

程序清单或不知道如何添加应用程序清单,您将需要添加应用程序清单。由于某些项目不会自动添加单独的清单文件,因此首先转到项目属性,导航到“应用程序”选项卡,然后检查以确保您的项目不排除点击底部的清单。

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

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.

  • Next, right click project
  • Add new Item
  • Last, find and click Application Manifest File
习惯那些不曾习惯的习惯 2025-01-01 20:34:18

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

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

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

打开该文件并将此行 : 更改

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

为:

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

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

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

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

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.

三寸金莲 2025-01-01 20:34:18

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

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.

画离情绘悲伤 2025-01-01 20:34:18

如果您出于某种原因需要纯代码解决方案,这里有一个独立的类文件。只需在应用程序启动时调用“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);
    }
}

In case you want a code-only solution for some reason, here's a standalone class file. Just call "AdminRelauncher.RelaunchIfNotAdmin()" at application start:

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);
    }
}
初见你 2025-01-01 20:34:18

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

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

THIS DOES NOT FORCE APPLICATION TO WORK AS ADMINISTRATOR.
This is a simplified version of the this answer, above by @NG

public bool IsUserAdministrator()
{
    try
    {
        WindowsIdentity user = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(user);
        return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch
    {
        return false;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文