使用C#检查文件夹的访问权限

时间:2015-03-24 06:21:49

标签: c# .net permissions filesystems access-control

我需要检查特定用户(域或本地)是否在给定目录中提到了权限(读/写)。

即使用户从用户组(如管理员)继承权限,该方法也应该返回true。

answer工作正常,但仅限于当前用户

1 个答案:

答案 0 :(得分:0)

尝试波纹管功能

using System.IO;
using System.Security.AccessControl; 

     public static bool CheckWritePermissionOnDir(string path)
        {
            var writeAllow = false;
            var writeDeny = false;
            var accessControlList = Directory.GetAccessControl(path); Control
            if (accessControlList == null)
                return false;
            var accessRules = accessControlList.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
            if (accessRules == null)
                return false;

            foreach (FileSystemAccessRule rule in accessRules)
            {
                if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write)
                    continue;

                if (rule.AccessControlType == AccessControlType.Allow)
                    writeAllow = true;
                else if (rule.AccessControlType == AccessControlType.Deny)
                    writeDeny = true;
            }

            return writeAllow && !writeDeny;
        }