【问题标题】:Check for access rights on a folder using C#使用 C# 检查文件夹的访问权限
【发布时间】:2015-05-27 09:14:29
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案1】:

    试试下面的函数

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

    【讨论】:

    • 但这不会检查特定用户
    • 你可以使用这一行 SecurityIdentifier users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);然后在你检查权限之前在你的 foreach 语句中添加 if (if(rule.IdentityReference == users)
    猜你喜欢
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 2014-11-04
    • 2013-07-02
    • 2010-10-28
    • 2019-02-14
    • 2013-09-14
    • 1970-01-01
    相关资源
    最近更新 更多