读取C#中目录的权限

我注意到如果您更改特定目录的安全设置,您可以使该文件夹不再在Windows中“浏览”。 特别是,将管理员的“读取”权限更改为“拒绝”将使该文件夹无法访问。

我现在的问题是,我如何在代码中解决这个问题? 我跟着让我接近,但它仍然是不对的:

///  /// Takes in a directory and determines if the current user has read access to it (doesn't work for network drives) /// THIS IS VERY HACKY ///  /// directoryInfo object to the directory to examine /// true if read access is available, false otherwise public static bool IsDirectoryReadable(DirectoryInfo dInfo) { try { System.Security.AccessControl.DirectorySecurity dirSec = dInfo.GetAccessControl(); System.Security.Principal.WindowsIdentity self = System.Security.Principal.WindowsIdentity.GetCurrent(); System.Security.Principal.WindowsPrincipal selfGroup = new System.Security.Principal.WindowsPrincipal(self); // Go through each access rule found for the directory foreach (System.Security.AccessControl.FileSystemAccessRule ar in dirSec.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier))) { if (selfGroup.IsInRole((System.Security.Principal.SecurityIdentifier)ar.IdentityReference)) { // See if the Read right is included if ((ar.FileSystemRights & System.Security.AccessControl.FileSystemRights.Read) == System.Security.AccessControl.FileSystemRights.Read) { if (ar.AccessControlType == System.Security.AccessControl.AccessControlType.Allow) { // If all of the above are true, we do have read access to this directory return true; } else { return false; } } } } // If we didn't find anything return false; } catch { // If anything goes wrong, assume false return false; } } 

我跟上述情况很接近,但我仍然缺少一些巨大的东西。 如果我右键单击文件夹来设置权限,我会看到(在我的示例中)3个组或用户名:“Administrators,myUserName和SYSTEM”。 如果我为“管理员”或“myUserName”将“读取”设置为“拒绝”,则我无法再浏览该目录。 如果我只将“系统”设置为“拒绝”,我仍然可以浏览它。

似乎存在某种隐含的权限层次结构,其中myUserName或Administrator取代SYSTEM组/用户。

上面的代码查找为我的用户标识找到的第一个允许“读取”并返回true。 我也可以编写代码来查找Read的第一个“Deny”并返回false。

我可以设置一个文件夹为“ – 拒绝”为SYSTEM和读 – “允许”为其他两个帐户,仍然读取该文件夹。 如果我更改代码以查找Deny并且它首先遇到SYSTEM用户身份,我的函数将返回“false”,这是… false。 对于其他两个帐户,它可能很好地读取 – “允许”。

我仍然无法弄清楚的问题是,如何确定哪个用户身份权限优先于所有其他权限?

它变得非常棘手,因为ACL允许inheritance,但它们也有一个限制性最强的访问模型。 换句话说,如果您的资源的用户链中的任何地方都有DENY,无论有多少其他组可能给您一个ALLOW,您都会被拒绝。 有关MSDN上的子目录的文章很好 。

系统组与O / S流程相关,与您的用户帐户没有直接关系。 如果没有用户上下文,那就是O / S用来访问文件系统的东西。 由于您的应用程序作为“用户名”运行,因此权限来自它及其所在的组。除非我遗漏了某些内容,否则不要认为您需要在这种情况下检查系统。

更新:请记住, Directory.Exists()还将检查您是否有权读取目录。

问题不是权限层次结构。 问题是您的代码基于第一个匹配的角色返回true或false。 您确实需要评估所有权限。

我最近不得不处理这个问题…我在这里发布了我的代码。