原文:C# WinForm判断Win7下是否是管理员身份运行

如果程序不是以管理员身份运行,操作本地文件会提示:System.UnauthorizedAccessException异常

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

我们在 win7 下运行一些安装程序时,会发现首先弹出一个对话框,让用户确认是否同意允许这个程序改变你的计算机配置,但我们编写的应用程序默认是不会弹出这个提示的,也无法以管理员权限运行。本文介绍了 C# 程序如何设置来提示用户以管理员权限运行。

首先在项目中增加一个 Application Manifest File

默认的配置如下:

<?xml version="1.0" encoding="utf-8"?><asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">    <security>      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">        <!-- UAC Manifest Options            If you want to change the Windows User Account Control level replace the            requestedExecutionLevel node with one of the following.        <requestedExecutionLevel  level="asInvoker" uiAccess="false" />        <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />        <requestedExecutionLevel  level="highestAvailable" uiAccess="false" />            If you want to utilize File and Registry Virtualization for backward            compatibility then delete the requestedExecutionLevel node.        -->        <requestedExecutionLevel level="asInvoker" uiAccess="false" />      </requestedPrivileges>    </security>  </trustInfo></asmv1:assembly>

我们可以看到这个配置中有一个 requestedExecutionLevel 项,这个项用于配置当前应用请求的执行权限级别。这个项有3个值可供选择,如下表所示:

Value Description Comment
asInvoker The application runs with the same access token as the parent process. Recommended for standard user applications. Do refractoring with internal elevation points, as per the guidance provided earlier in this document.
highestAvailable The application runs with the highest privileges the current user can obtain. Recommended for mixed-mode applications. Plan to refractor the application in a future release.
requireAdministrator The application runs only for administrators and requires that the application be launched with the full access token of an administrator. Recommended for administrator only applications. Internal elevation points are not needed. The application is already running elevated.

asInvoker : 如果选这个,应用程序就是以当前的权限运行。

highestAvailable: 这个是以当前用户可以获得的最高权限运行。

requireAdministrator: 这个是仅以系统管理员权限运行。

默认情况下是 asInvoker。

highestAvailable 和 requireAdministrator 这两个选项都可以提示用户获取系统管理员权限。那么这两个选项的区别在哪里呢?

他们的区别在于,如果我们不是以管理员帐号登录,那么如果应用程序设置为 requireAdministrator ,那么应用程序就直接运行失败,无法启动。而如果设置为 highestAvailable,则应用程序可以运行成功,但是是以当前帐号的权限运行而不是系统管理员权限运行。如果我们希望程序在非管理员帐号登录时也可以运行(这种情况下应该某些功能受限制) ,那么建议采用 highestAvailable 来配置。

关于requestedExecutionLevel 设置的权威文档请参考下面链接:

Create and Embed an Application Manifest (UAC)

下面是修改后的配置文件:

<?xml version="1.0" encoding="utf-8"?><asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">    <security>      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">        <!-- UAC Manifest Options            If you want to change the Windows User Account Control level replace the             requestedExecutionLevel node with one of the following.        <requestedExecutionLevel  level="asInvoker" uiAccess="false" />        <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />        <requestedExecutionLevel  level="highestAvailable" uiAccess="false" />            If you want to utilize File and Registry Virtualization for backward             compatibility then delete the requestedExecutionLevel node.        -->        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />      </requestedPrivileges>    </security>  </trustInfo></asmv1:assembly>

配置文件修改后,我们运行应用程序,就会首先弹出这样一个提示框,点 Yes 后,程序才可以继续运行,并且获得系统管理员的权限。

下面再来看看程序如何知道当前运行在系统管理员权限还是非系统管理员权限:
using System.Security.Principal

public static bool IsAdministrator(){    WindowsIdentity identity = WindowsIdentity.GetCurrent();    WindowsPrincipal principal = new WindowsPrincipal(identity);    return principal.IsInRole(WindowsBuiltInRole.Administrator);}

这段代码可以用于判断当前程序是否运行在系统管理员权限下。如果配置为 asInvoker,在win7 下,这个函数会返回 false ,如果是 requireAdministrator  则返回 true。

参考:http://msdn.microsoft.com/zh-cn/library/system.security.principal.windowsidentity.aspx
url:http://greatverve.cnblogs.com/archive/2011/12/28/win7-admin.html

C# WinForm判断Win7下是否是管理员身份运行的更多相关文章

  1. Win7下判断当前进程是否以管理员身份运行

    判断当前程序是否以管理员身份运行,代码如下: #include <iostream> #include <windows.h> using namespace std; // ...

  2. win7如何设置以管理员身份运行

    一.对所有程序以管理员身份运行 1.右键单击桌面“计算机”,选择“管理” 2.在页面左侧,依此打开“计算机管理(本地)→ 系统工具→本地用户和组→用户”,在右侧找到“Administrator”,双击 ...

  3. win8下始终以管理员身份运行vs2012的解决办法

    因为我的windows8不是专业版的,不能通过网上方法修改组策略,所以尝试了下面的方法: 1. 在vs2012快捷方式上,右键选择兼容性疑难解答: 2. 等待检测完,选择故障排除选项页面,选“疑难解答 ...

  4. C#判断程序是否以管理员身份运行,否则以管理员身份重新打开

    /// <summary> /// 判断程序是否是以管理员身份运行. /// </summary> public static bool IsRunAsAdmin() { Wi ...

  5. C# 让程序自动以管理员身份运行

    exe在Vista或Win7下不以管理员权限运行,会被UAC(用户帐户控制)阻止访问系统某些功能,如修改注册表操作等;如何让exe以管理员权限运行呢,方法有两种,一个是直接修改exe属性;另一个是在程 ...

  6. Win7 下以管理员身份运行批处理文件,切换JDK版本

    Win7下 切换JDK的批处理命令 1. 批处理文件(必须以管理员身份执行)内容如下 @echo off rem --- Base Config 配置JDK的安装目录 --- :init set JA ...

  7. win7下让程序默认以管理员身份运行

    在win7中用自己写的程序读取MBR时,突然提示无法对磁盘进行操作,而在xp下并没有这个问题:最后点右键以管理员身份运行才可以正常运行.于是想办法让程序在双击启动时默认以管理员身份运行.具体方法: 1 ...

  8. 【VS开发】win7下让程序默认以管理员身份运行

    在win7中用自己写的程序读取MBR时,突然提示无法对磁盘进行操作,而在xp下并没有这个问题:最后点右键以管理员身份运行才可以正常运行.于是想办法让程序在双击启动时默认以管理员身份运行.具体方法: 1 ...

  9. win7 64位下vs不能以管理员身份运行的问题解决

    开发机上安装了VS6.0/2008/2010/2013,之前一直是正常的,突然莫名其妙不能以管理员身份运行(除了VS6),报"application cannot start.", ...

随机推荐

  1. cdh 上安装spark on yarn

    在cdh 上安装spark on yarn 还是比较简单的,不需要独立安装什么模块或者组件. 安装服务 选择on yarn 模式:上面 Spark 在spark 服务中添加 在yarn 服务中添加 g ...

  2. 关于C语言中有string类型吗?

    一.问题来源 今天在VS2010平台上,尝试采用scanf() string word; scanf("%s",&word); 然后发现错误,输出采用 printf(&qu ...

  3. 浅谈C中的指针和数组(二)

    原文转载地址:http://see.xidian.edu.cn/cpp/html/475.html 在原文的基础上增加自己的想法作为修改 很多初学者弄不清指针和数组到底有什么样的关系.我现在就告诉你: ...

  4. OC语法1——OC概述

    Object-C简介: OC,即Object-C,iOS开发的核心语言.它是基于C语言的,在C的基础上做了面向对象的封装,所以OC是面向对象的语言.同时也因此OC是兼容C的,也就是说在iOS开发中,可 ...

  5. 图片压缩上传 Android

    图片压缩的话 想保持 图像清晰度,但是又想保持图片的大小在100k左右. 同时的话又不想自己写那些压缩的代码的话.那你就找对地方了. 提供一个思路. 先读取你的文件,然后读到bitmap里面进行尺寸裁 ...

  6. Android ORM SQL Top 5

    If you are developing an Android application, you will likely need to store data somewhere. You may ...

  7. WIN7/8系统下程序接收不到WM_COPYDATA 消息的原因和解决

    在WIN7/win8,如果发送消息的程序用户权限低于和接收消息的程序,则消 息无法传递.发送程序必须等于或者等于接收程序的权限.如发送与接收 是同一个用户,或者发送是管理员帐户,接收是是普通用户,这样 ...

  8. php数组array,知道键名如何提取键值

    如果是知道键值,需要查找键名,直接使用array_search()即可.现在反过来,如何操作?   (1)array_walk_recursive()加自定义函数查找   $arr=array( 'n ...

  9. c++中多态性、dynamic_cast、父类指针、父类对象、子类指针、子类对象

    c++多态性是依靠虚函数和父类指针指向子类对象来实现的.简单来说,父类中定义虚函数,父类指针指向子类对象,父类指针调用函数时调用的就是子类的函数. 父类没有定义虚函数,父类指针指向子类对象时,父类指针 ...

  10. libcurl编译

    下载: git://github.com/bagder/curl.git openssl: openssl编译   for linux or mingw:./buildconf./configure ...