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

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

下面演示 C# 程序如何实现提示用户以管理员权限运行。

本例以WinForm程序演示,新建一项目生成后进行相应修改:

方法一:通过 System.Diagnostics.Process.Start() 方式启动:

实现方法: 修改默认生成的Program文件,修改后的代码如下:

由于已经在代码上做了注释,所以不再详细说明;

 1     static class Program
 2     {
 3         [STAThread]
 4         static void Main()
 5         {            
 6             Application.EnableVisualStyles();
 7             Application.SetCompatibleTextRenderingDefault(false);
 8 
 9             /**
10              * 当前用户是管理员的时候,直接启动应用程序
11              * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
12              */
13             //获得当前登录的Windows用户标示
14             System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
15             System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
16             //判断当前登录用户是否为管理员
17             if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
18             {
19                 //如果是管理员,则直接运行
20                 Application.Run(new Form1());
21             }
22             else
23             {
24                 //创建启动对象
25                 System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
26                 startInfo.UseShellExecute = true;
27                 startInfo.WorkingDirectory = Environment.CurrentDirectory;
28                 startInfo.FileName = Application.ExecutablePath;
29                 //设置启动动作,确保以管理员身份运行
30                 startInfo.Verb = "runas";
31                 try
32                 {
33                     System.Diagnostics.Process.Start(startInfo);
34                 }
35                 catch
36                 {
37                     return;
38                 }
39                 //退出
40                 Application.Exit();
41             }
42         }
43     }

效果:由于是通过System.Diagnostics.Process.Start() 方式外部调用启动,所以直接通过VS运行时,是不会提示VS也需要管理员权限,只有程序本身需要管理员权限,与生成应用程序的程序不同。这点是和方法二实现的主要不同之处。

本文地址:http://www.cnblogs.com/Interkey/p/RunAsAdmin.html

方法二:通过添加应用程序清单文件:

在 项目 上 添加新项 选择“应用程序清单文件” 然后单击 添加 按钮

添加后,默认打开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;
    }

 


 

 

如果有兴趣还可以继续查看下面的链接:

http://www.cnblogs.com/Lemon_s/archive/2011/07/28/2119222.html

http://www.cnblogs.com/shenchao/archive/2013/03/05/2944660.html

希望能帮到大家~~~

posted on 2013-07-13 21:39  Cosmic_Spy  阅读(45548)  评论(12编辑  收藏  举报

导航

Your IP: