C#目录安全性SetAccessControl没有生效?

时间:2014-05-14 18:43:45

标签: c# permissions

我正在尝试更改目录的权限。为此,我正在运行一个实际执行SetAccessControl的高级进程。

    static void Main(string[] args)
    {
        var options = new Options();
        if (!CommandLine.Parser.Default.ParseArguments(args, options)) return;

        var myDirectoryInfo = new DirectoryInfo(options.folder);
        var myDirectorySecurity = myDirectoryInfo.GetAccessControl();
        var usr = options.user;

        myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(usr, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));

        try
        {
            myDirectoryInfo.SetAccessControl(myDirectorySecurity);
        }
        catch (Exception ex)
        {               
           Console.WriteLine(ex.Message);
        }

    }

当我以管理员身份运行时,没有错误,但文件夹访问权限保持不变。有什么想法是错的吗?

2 个答案:

答案 0 :(得分:3)

对我有用的答案是使用ModifyAccessRule首先授予该目录的权限。然后添加继承规则。

此外,我发现Windows资源管理器并不总是显示当前权限,不确定是什么原因导致它刷新,但我注意到有时权限设置正确,我的程序可以访问目录中的文件,即使探险家没有表示同意。

    private static bool SetAccess(string user, string folder)
    {
        const FileSystemRights Rights = FileSystemRights.FullControl;

        // *** Add Access Rule to the actual directory itself
        var AccessRule = new FileSystemAccessRule(user, Rights,
            InheritanceFlags.None,
            PropagationFlags.NoPropagateInherit,
            AccessControlType.Allow);

        var Info = new DirectoryInfo(folder);
        var Security = Info.GetAccessControl(AccessControlSections.Access);
        bool Result;

        Security.ModifyAccessRule(AccessControlModification.Set, AccessRule, out Result);

        if (!Result) return false;

        // *** Always allow objects to inherit on a directory
        const InheritanceFlags iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

        // *** Add Access rule for the inheritance
        AccessRule = new FileSystemAccessRule(user, Rights,
            iFlags,
            PropagationFlags.InheritOnly,
            AccessControlType.Allow);

        Security.ModifyAccessRule(AccessControlModification.Add, AccessRule, out Result);

        if (!Result) return false;

        Info.SetAccessControl(Security);

        return true;
    } 

答案 1 :(得分:-1)

使用以下代替myDirectoryInfo.SetAccessControl(myDirectorySecurity);

try
{
    Directory.SetAccessControl(options.folder,myDirectorySecurity);
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}