UnauthorizedAccessException使用DirectorySecurity库尝试获取访问规则时

时间:2016-09-15 18:01:13

标签: c# authentication active-directory

我正在尝试使用获取访问规则的方法为用户获取特定文件夹写入权限,并检查登录用户是否具有该文件夹的写入权限。但是当我尝试这样做时,我收到一条错误,声明UnauthorizedException。我已经检查了文件夹访问权限,一切看起来都不错。我在下面是错误的屏幕截图:

enter image description here

 private bool AccessPackerPlanTemplate()
        {
            bool result = true;
            UserBUList userBUList = new UserBUList();

            try
            {
                string PackerPlanTemplate = System.Configuration.ConfigurationSettings.AppSettings["PackerPlanTemplate"];

                userBUList.UserName = (HttpContext.Current.User.Identity).Name.Split('\\')[1].ToString();
                string path = PackerPlanTemplate;
                string NtAccountName = userBUList.UserName;

                DirectoryInfo di = new DirectoryInfo(path);
                DirectorySecurity acl = di.GetAccessControl(AccessControlSections.All);         //I AM GETTING ERROR ON THIS LINE        
                System.Security.AccessControl.AuthorizationRuleCollection rules = acl.GetAccessRules(true, true, typeof(NTAccount));

                //Go through the rules returned from the DirectorySecurity
                foreach (System.Security.AccessControl.AuthorizationRule rule in rules)
                {
                    //If we find one that matches the identity we are looking for
                    if (rule.IdentityReference.Value.Equals(NtAccountName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        //Cast to a FileSystemAccessRule to check for access rights
                        if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.WriteData) > 0)
                        {
                            result = true ;
                        }
                    }

                }
            }
            catch (UnauthorizedAccessException)
            {
                result = false;
            }
            return result;
        }

有人对我在哪里出错有任何建议吗?有更好的方法吗?

0 个答案:

没有答案