检查文件/文件夹访问权限

我得到一个运行此代码的UnautorizedAccessException

 string[] fileList = Directory.GetFiles(strDir, strExt); 

c:\users\username\appdata发生exception如何检查我是否具有访问权限(列出和读取文件)?

首先,我会手动检查权限,看看是什么阻止了你,什么不阻止。 我正在使用这样的东西来检查权限(对于复制文件):

 AuthorizationRuleCollection acl = fileSecurity.GetAccessRules(true, true,typeof(System.Security.Principal.SecurityIdentifier)); bool denyEdit = false; for (int x = 0; x < acl.Count; x++) { FileSystemAccessRule currentRule = (FileSystemAccessRule)acl[x]; AccessControlType accessType = currentRule.AccessControlType; //Copy file cannot be executed for "List Folder/Read Data" and "Read extended attributes" denied permission if (accessType == AccessControlType.Deny && (currentRule.FileSystemRights & FileSystemRights.ListDirectory) == FileSystemRights.ListDirectory) { //we have deny copy - we can't copy the file denyEdit = true; break; } ... more checks } 

此外,还有一些奇怪的情况,文件夹上的某个权限会更改文件的权限,无论其个人权限如何(将查看我是否可以找到它的内容)。

查看关于代码项目的文章,这是关于你需要的东西,是为此创建的类:这个类的目的是为常见问题提供一个简单的答案,“我是否有权读取或写入此文件?”。

一种测试给定文件和用户的个人访问权限的简单方法

注意:不能在这里发布整个代码,因为它太长了。

首先,为根目录调用Directory.GetFiles 。 Catch UnauthorizedAccessException – 如果没有,则您具有完全访问权限。

如果捕获 – 以递归方式调用每个子目录的函数,捕获exception,如果捕获 – 将此类目录添加到列表中。

使用外部列表为禁止的dirs写一个递归函数