订阅到Rss阅读器

戏水的技术点点

善恶本难分 做佛先做人 虚空生万法 不着诗与文
随笔 - 81, 文章 - 17, 评论 - 560, 引用 - 3
数据加载中……

C#设置与获取目录权限(.net控制ACL)

想用c#来设置和读取ntfs分区上的目录权限,找了很多资料,未果。终于发现了一段vb.net的代码,做了修改,以C#展示给大家。

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(truetruetypeof(System.Security.Principal.NTAccount)))
        
{
            Console.WriteLine(
"----------------------------------");
            Console.WriteLine(rule.IdentityReference.Value);
            
if ((rule.FileSystemRights & FileSystemRights.Read) != 0)
                Console.WriteLine(rule.FileSystemRights.ToString());

        }

        Console.Read();
    }


}


对照MSDN,很容易看懂上面的代码。 但是貌似这个程序需要以管理员身份来运行。^_^

其中的Directory.GetAccessControl(FileName, AccessControlSections.All);  第二个参数如果为AccessControlSections.Access ,就可以使得运行在IIS中的Web应用程序获得目录权限了。

posted on 2008-03-06 12:38 戏水 阅读(2829) 评论(13)  编辑 收藏 所属分类: Dotnet

评论

#1楼    回复  引用  查看    

其实如果你安装了 .Net SDK 帮助文档里就有
ms-help://MS.NETFramework.v20.chs/cpref11/html/T_System_Security_AccessControl_FileSystemRights.htm#codeExampleToggle
2008-03-06 12:54 | Microshaoft      

#2楼    回复  引用  查看    

我的园子里面有一个相关的方法,你看看你能不能用,我觉得还不错。

http://www.cnblogs.com/bluesky4485/archive/2008/03/06/1093544.html
2008-03-06 14:51 | bluesky4485      

#3楼 [楼主]   回复  引用  查看    

@bluesky4485
我觉得不喜欢您那个方法。
2008-03-06 15:30 | 戏水      

#4楼    回复  引用  查看    

跟我当年干的事一样,当年我也是费了半天劲把这段代码转成c#了。。。。
2008-03-06 15:55 | 第一控制.NET      

#5楼    回复  引用  查看    

mark
2008-03-06 16:20 | chy710      

#6楼    回复  引用  查看    

我在做一个文件复制管理器,这段代码对我有用......
2008-03-06 16:32 | 蓝天旭日      

#7楼    回复  引用    

人家未必使用Administrator这个用户名哦。
你还要遍历系统中的用户名吧?
搞不好就带出安全问题了。。
2008-03-07 09:48 | bighead [未注册用户]

#8楼    回复  引用    

对照MSDN,很容易看懂上面的代码。 但是貌似这个程序需要以管理员身份来运行。^_^
----------------------------------------
--引用--------------------------------------------------
bighead: 人家未必使用Administrator这个用户名哦。
你还要遍历系统中的用户名吧?
搞不好就带出安全问题了。。
--------------------------------------------------------

只要程序带着管理员的登录令牌,程序才不管你当前登录的用户权限有多低
2008-03-07 10:19 | Sleet [未注册用户]

#9楼    回复  引用    

路过 学习
2008-03-07 14:16 | look look [未注册用户]

#10楼    回复  引用    

直接调用Win32的Api,可以通过网络获取
/// <summary>
/// 使用Win32Api获取指定文件夹的安全权限。
/// </summary>
/// <param name="serverPath">计算机的DNS名称或NetBIOS名称或IP。null和"."可以表示本地。</param>
/// <param name="folderPath">指定文件夹的绝对路径或UNC路径。</param>
/// <param name="identityType">身份类别。默认System.Security.Principal.NTAccount。</param>
/// <param name="inheritances">是否是继承的。顺序与返回值一致。</param>
/// <returns>FileSystemAccessRule - Inherited</returns>
/// <remarks>
/// serverPath与folderPath构成文件夹的绝对路径或UNC路径。
/// 绝对路径,"\\computer_name\g:\remote_dir\"
/// UNC路径,"share_name\dir"或"\\computer_name\share_name\dir"
/// 如果是本地"\\computer_name"可以用"\\."表示。
/// 绝对路径会在方法调用时转化为UNC路径,方法是将驱动器盘符换成相应的默认共享。即
/// "\\computer_name\g:\remote_dir\" --> "\\computer_name\g$\remote_dir\"。
/// 因此如果使用绝对路径需要保证存在相应的默认共享。</remarks>
public static List<FileSystemAccessRule> GetFolderNTFSDaclByWin32(string serverPath, string folderPath,
Type identityType, out List<bool> inheritances)
{
List<FileSystemAccessRule> rules = new List<FileSystemAccessRule>();
inheritances = new List<bool>();

Microsoft.Win32.Security.SecurityDescriptor desc = Microsoft.Win32.Security.SecurityDescriptor.GetNamedSecurityInfo(
Utils.GenerateUNCPath(serverPath, folderPath),
Microsoft.Win32.Security.SE_OBJECT_TYPE.SE_FILE_OBJECT,
Microsoft.Win32.Security.SECURITY_INFORMATION.DACL_SECURITY_INFORMATION);

if (desc != null)
{
Microsoft.Win32.Security.Dacl dacl = desc.Dacl;
IEnumerator ie = dacl.GetEnumerator();
while (ie.MoveNext())
{
Microsoft.Win32.Security.AceAccess access = (Microsoft.Win32.Security.AceAccess)ie.Current;

InheritanceFlags inheritanceFlags;
PropagationFlags propagationFlags;
ParseAceFlags((byte)access.Flags, out inheritanceFlags, out propagationFlags);

FileSystemAccessRule perm = new FileSystemAccessRule(
((identityType != null || identityType.GetType() == typeof(System.Security.Principal.SecurityIdentifier)) ?
(System.Security.Principal.IdentityReference)(new System.Security.Principal.SecurityIdentifier(access.Sid.SidString)) :
(System.Security.Principal.IdentityReference)(new System.Security.Principal.NTAccount(access.Sid.DomainName, access.Sid.AccountName))),
(System.Security.AccessControl.FileSystemRights)access.AccessType,
inheritanceFlags,
propagationFlags,
(access.IsAllowed ? System.Security.AccessControl.AccessControlType.Allow : System.Security.AccessControl.AccessControlType.Deny));

rules.Add(perm);
inheritances.Add(access.IsInherited);
}
}
return rules;
}
2008-03-07 17:12 | sheriwnzhu [未注册用户]

#11楼    回复  引用  查看    

不知道能不能在.net 1.1 下面操作文件的权限??
2008-03-30 15:02 | openkava      

标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2008-03-08 10:11 编辑过


相关链接: