C#程序以管理员权限运行

在Vista 和 Windows 7 及更新版本的操作系统,增加了 UAC(用户账户控制) 的安全机制,如果 UAC 被打开,用户即使以管理员权限登录,其应用程序默认情况下也无法对系统目录、系统注册表等可能影响系统正常运行的设置进行写操作。这个机制大大增强了系统的安全性,但对应用程序开发者来说,我们不能强迫用户去关闭UAC,但有时我们开发的应用程序又需要以 Administrator 的方式运行,如何实现这样的功能呢?

下面演示 C# 程序如何实现提示用户以管理员权限运行。 本例以WinForm程序演示,新建一项目生成后进行相应修改: 方法一:通过 System.Diagnostics.Process.Start() 方式启动: 实现方法: 修改默认生成的Program文件,修改后的代码如下:

static class Program
    {
        [STAThread]
        static void Main()
        {            
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            /**
             * 当前用户是管理员的时候,直接启动应用程序
             * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
             */
            //获得当前登录的Windows用户标示
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            //判断当前登录用户是否为管理员
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                //如果是管理员,则直接运行
                Application.Run(new Form1());
            }
            else
            {
                //创建启动对象
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.UseShellExecute = true;
                startInfo.WorkingDirectory = Environment.CurrentDirectory;
                startInfo.FileName = Application.ExecutablePath;
                //设置启动动作,确保以管理员身份运行
                startInfo.Verb = "runas";
                try
                {
                    System.Diagnostics.Process.Start(startInfo);
                }
                catch
                {
                    return;
                }
                //退出
                Application.Exit();
            }
        }
    }

效果:由于是通过System.Diagnostics.Process.Start() 方式外部调用启动,所以直接通过VS运行时,是不会提示VS也需要管理员权限,只有程序本身需要管理员权限,与生成应用程序的程序不同。这点是和方法二实现的主要不同之处。 方法二:通过添加应用程序清单文件: 在 项目 上 添加新项 选择“应用程序清单文件” 然后单击 添加 按钮 添加后,默认打开app.manifest文件,将: <requestedExecutionLevel level="asInvoker" uiAccess="false" /> 修改为: <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> 然后打开 项目属性 ,将 应用程序 标签页中的 资源 中的 清单 修改为新建的 app.manifest。 重新生成项目,再次打开程序时就会提示 需要以管理员权限运行。 需要注意的是:如果在VS中 启动调试 的话,就会提示 此任务要求应用程序具有提升的权限。如下图:

输入图片说明 选择 使用其他凭据重新启动 即可。 方法三:直接修改程序文件的属性 右击程序文件,在弹出的属性对话框中的 兼容性 标签页中 勾选“以管理员身份运行此程序”即可。

输入图片说明

判断程序是否以管理员身份运行 需要添加命名空间: using System.Security.Principal;

/// <summary>
    /// 确定当前主体是否属于具有指定 Administrator 的 Windows 用户组
    /// </summary>
    /// <returns>如果当前主体是指定的 Administrator 用户组的成员,则为 true;否则为 false。</returns>
    public static bool IsAdministrator()
    {
        bool result;
        try
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            result = principal.IsInRole(WindowsBuiltInRole.Administrator);

            //http://www.cnblogs.com/Interkey/p/RunAsAdmin.html
            //AppDomain domain = Thread.GetDomain();
            //domain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            //WindowsPrincipal windowsPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;
            //result = windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
        }
        catch
        {
            result = false;
        }
        return result;
    }

转载于:https://my.oschina.net/Maculish/blog/549145

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#程序中请求管理员权限可以通过在app.manifest文件中设置请求管理员权限,或者使用代码请求管理员权限。 方法一:在app.manifest文件中设置请求管理员权限 在项目中的app.manifest文件中,找到下面的代码块,并将requestedExecutionLevel的level属性设置为requireAdministrator。 ```xml <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> ``` 方法二:使用代码请求管理员权限 使用代码请求管理员权限需要使用Windows API函数,可以使用下面的代码: ```csharp using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace AdminLauncher { class Program { [DllImport("user32.dll", SetLastError = true)] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetConsoleWindow(); static void Main(string[] args) { if (!IsAdmin()) { StartAsAdmin(); return; } // 操作管理员权限下的资源 } static bool IsAdmin() { var identity = System.Security.Principal.WindowsIdentity.GetCurrent(); var principal = new System.Security.Principal.WindowsPrincipal(identity); return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator); } static void StartAsAdmin() { var fileName = Process.GetCurrentProcess().MainModule.FileName; var startInfo = new ProcessStartInfo { UseShellExecute = true, WorkingDirectory = Environment.CurrentDirectory, FileName = fileName, Verb = "runas" }; Process.Start(startInfo); ShowWindow(GetConsoleWindow(), 0); } } } ``` 以上代码中,IsAdmin方法用于判断当前程序是否以管理员权限运行,如果是,则执行管理员权限下的操作,否则调用StartAsAdmin方法以管理员权限重新启动程序。StartAsAdmin方法使用ProcessStartInfo对象来设置启动参数,其中Verb属性设置为"runas"表示以管理员权限启动程序。注意,使用Verb属性可能会弹出UAC提示框,需要用户授权才能继续执行,如果不想显示UAC提示框,可以使用Windows API函数ShowWindow将控制台窗口隐藏。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值