WindowsIdentity类可以获取当前执行者的身份信息

  1. /// <summary>
  2. /// 递归搜索文件方法
  3. /// </summary>
  4. /// <param name="path">搜索的目录</param>
  5. /// <param name="name">搜索的文件名</param>
  6. public void GetDir(string path,string name)
  7. {
  8. DirectoryInfo di = new DirectoryInfo(path);
  9. DirectorySecurity s = new DirectorySecurity(path, AccessControlSections.Access);
  10. //判断目录是否 可以访问
  11. if (!s.AreAccessRulesProtected)
  12. {
  13. foreach (DirectoryInfo d in di.GetDirectories())
  14. {
  15. foreach (FileInfo fi in di.GetFiles())
  16. {
  17. if (fi.Name.Contains(name))
  18. {
  19. txtInfo.AppendText("文件名:"+fi.Name + " 路径:" + fi.FullName + " \n");
  20. }
  21. }
  22. GetDir(d.FullName, name);
  23. }
  24. }
  25. }

对执行的程序设定执行身份权限

如果程序不是以管理员身份运行,操作本地文件会提示: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。

using System;
using System.Collections;
using System.IO;
using System.Security.AccessControl;
static class Tester
{

public static void Main()
    {
        try
        {
            string filename = @"f:\k"; //目标目录
            string account = @"Administrator";//用户名
            string userrights = @"RW";//权限字符串,自己定义的
            AddDirectorySecurity(filename, account, userrights);
            Console.ReadLine();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            Console.ReadLine();
        }
    }

static public void AddDirectorySecurity(string FileName, string Account, string UserRights)
    {
        FileSystemRights Rights = new FileSystemRights();

if (UserRights.IndexOf("R") >= 0)
        {
            Rights = Rights | FileSystemRights.Read;
        }
        if (UserRights.IndexOf("C") >= 0)
        {
            Rights = Rights | FileSystemRights.ChangePermissions;
        }
        if (UserRights.IndexOf("F") >= 0)
        {
            Rights = Rights | FileSystemRights.FullControl;
        }
        if (UserRights.IndexOf("W") >= 0)
        {
            Rights = Rights | FileSystemRights.Write;
        }

bool ok;
        DirectoryInfo dInfo = new DirectoryInfo(FileName);
        DirectorySecurity dSecurity = dInfo.GetAccessControl();
        InheritanceFlags iFlags = new InheritanceFlags();
        iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
        FileSystemAccessRule AccessRule2 = new FileSystemAccessRule(Account, Rights, iFlags, PropagationFlags.None, AccessControlType.Allow);
        dSecurity.ModifyAccessRule(AccessControlModification.Add, AccessRule2, out ok);

dInfo.SetAccessControl(dSecurity);

//列出目标目录所具有的权限
        DirectorySecurity sec = Directory.GetAccessControl(FileName, AccessControlSections.All);
        foreach (FileSystemAccessRule rule in sec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
        {
            Console.WriteLine("----------------------------------");
            Console.WriteLine(rule.IdentityReference.Value);
            if ((rule.FileSystemRights & FileSystemRights.Read) != 0)
                Console.WriteLine(rule.FileSystemRights.ToString());
        }
        Console.Read();
    }
}

 
 

C# Winform对文件夹的权限判断及处理的更多相关文章

  1. linux系统下修改文件夹目录权限

    linux系统下修改文件夹目录权限 文件夹权限问题 Linux.Fedora.Ubuntu修改文件.文件夹权限的方法差不多.很多人开始接触Linux时都很头痛Linux的文件权限问题.这里告诉大家如何 ...

  2. C#修改文件或文件夹的权限,为指定用户、用户组添加完全控制权限

    C#修改文件或文件夹的权限,为指定用户.用户组添加完全控制权限 public void SetFileRole(string foldPath) { DirectorySecurity fsec = ...

  3. CMD命令下对文件夹进行权限处理 转

    保证自己的磁盘分区格式是NTFS.FAT32是不行的. 一.Cacls.exe命令的使用 这是一个在Windows 2000/XP/Server 2003操作系统下都可以使用的命令,作用是显示或者修改 ...

  4. Linux中文件夹访问权限不足

    经常操作Linux服务器,远程访问会遇到403问题,本篇讲述nginx下文件权限的修改. 1.命令修改该文件夹的权限 chmod -R 755 /usr/local/....   文件夹的路径 2.修 ...

  5. 设置SharePoint部门站点各个文件夹的权限

    最近跟客户设置了下部门站点文件夹的权限,现整理一下实现步骤: 1. Site actions –> site permissions: 停止继承,并把部门所有员工都授予Read权限: 2. 在S ...

  6. 获取AFP共享的文件夹及其权限

    获取AFP共享的文件夹及其权限   获取AFP服务的认证信息后,渗透测试人员就可以使用afp-showmount脚本获取共享的文件夹信息,以及各级用户权限信息.其中,用户包括所有者.组.Everyon ...

  7. 修改Linux下的文件以及文件夹的权限

    如何在Linux中管理文件和文件夹的权限? 2014-02-12 10:58 布加迪编译 51CTO 字号:T | T Linux系统有严格的权限管理制度,操作者权限与文件权限不匹配时将无法对文件进行 ...

  8. linux系统下修改文件夹目录权限-chmod

    Linux.Fedora.Ubuntu修改文件.文件夹权限的方法差不多.很多人开始接触Linux时都很头痛Linux的文件权限问题.这里告诉大家如何修改Linux文件-文件夹权限.以主文件夹下的一个名 ...

  9. Ubuntu下如何修改文件或者文件夹的权限

    Ubuntu下如何修改文件或者文件夹的权限------chmod的亲身测试   具体原理如下: Linux系统下如何修改文档及文件夹(含子文件夹)权限,我们来看一下.              一 介 ...

随机推荐

  1. UML学习-状态图

    1.状态图概述 状态图(Statechart Diagram)主要用于描述一个对象在其生存期间的动态行为,表现为一个对象所经历的状态序列,引起状态转移的事件(Event),以及因状态转移而伴随的动作( ...

  2. (原创)ubuntu 12.04 安装 apache ant

    1. go to the websie to download the newest version of ant (search google by "Apache Ant"). ...

  3. UVA11401Triangle Counting(简单计数)

    转载请注明出处: http://www.cnblogs.com/fraud/          ——by fraud 题目意思:从1,2,3,……,n中选出3个不同的整数使其构成一个三角形,有多少种方 ...

  4. C语言实现界面(不通过MFC\避免遗忘)

    感觉MFC不属于程序员细究的东西,今实现基本界面避免日后遗忘. 源代码: #include<windows.h>#include<stdio.h>char str[] = {' ...

  5. java学会需要掌握的知识(来源网上。。)

    Java就业指导 2016-03-22 骆昊 程序人生 点击上方"程序人生"关注我们 想要成为合格的Java程序员或工程师到底需要具备哪些专业技能,面试者在面试之前到底需要准备哪些 ...

  6. CI(CodeIgniter)学习第一讲

    一.CI的优势一. (1).CI是一个PHP框架:大家都知道PHP框架有很多,CI只是其中之一,框架是为了重用发明的.同样,CI的目标是实现让你比从零开始编写代码更快速地开发项目.CI可以将需要完成的 ...

  7. 高可用集群(HA)之DRBD原理和基础配置

    目录 1.工作原理图 2.用户空间工具 3.工作模式 4.实现主备故障自动切换 5.所需软件 6.配置文件 7.详细配置     1.配置通用属性信息     2.定义一个资源     3.初始化资源 ...

  8. C#两个时间的时间差的方法

    今天遇到一问题,计算两个时间的时间差,看网上的写法较为复杂,找到个简单点的,记录下作为自己的总结. 关键函数: DateTime.Subtract 函数解释: 从此实例中减去指定的日期和时间,返回一个 ...

  9. 机器学习 1、R语言

    R语言 R是用于统计分析.绘图的语言和操作环境.R是属于GNU系统的一个自由.免费.源代码开放的软件,它是一个用于统计计算和统计制图的优秀工具. 特点介绍 •主要用于统计分析.绘图.数据挖掘 •R内置 ...

  10. 查看Java包源码