Check for access rights on a folder using C#

天涯浪子 提交于 2019-12-10 11:48:02

问题


I need check if a specific user (Domain or Local), has mentioned rights (Read / Write) on the given directory.

The method should return true even the User is inheriting the rights from User Group (like Administrators).

This answer works fine but it is limited to Current User only


回答1:


Try the bellow function

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;
        }


来源:https://stackoverflow.com/questions/29226208/check-for-access-rights-on-a-folder-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!