2

在结束我的问题之前,请查看我检查的内容,并且在这个问题的末尾不起作用


问题

我一直在尝试各种 SO 答案,所有这些都给我带来了一个例外,除了其中许多听起来过于复杂,因为它应该非常简单。

如何在执行之前检查我是否有权枚举文件夹的内容?(我不想尝试/捕获,因为我正在遍历文件系统并且多次尝试/捕获会影响 C# 的性能)

每当我尝试以下操作时:

//where dir is a DirectoryInfo instance
foreach (FileInfo file in dir.EnumerateFiles())

我得到这个例外:

mscorlib.dll 中出现“System.UnauthorizedAccessException”类型的未处理异常
附加信息:O acesso ao caminho 'e:\$RECYCLE.BIN\S-1-5-18' foi negado。
translation:“访问路径 'e:\$RECYCLE.BIN\S-1-5-18' 被拒绝”


什么不起作用:

1:

当我这样做时,代码进入if并在遇到枚举时抛出相同的异常。

PermissionSet permissions = new PermissionSet(System.Security.Permissions.PermissionState.None);
permissions.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, dir.FullName));

if (permissions.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))

2:

以下引发异常:

DirectorySecurity security = dir.GetAccessControl(AccessControlSections.All); 

例外:

mscorlib.dll 中发生了“System.Security.AccessControl.PrivilegeNotHeldException”类型的未处理异常
附加信息:O processo não possui o privilégio 'SeSecurityPrivilege' necessário para esta opacão。
translation:该进程没有此操作所需的“SeSecurityPrivilege”特权。

与:

    DirectorySecurity security = dir.GetAccessControl(AccessControlSections.None); 

例外:

在 mscorlib.dll 中发生类型为“System.UnauthorizedAccessException”的未处理异常
附加信息:Tentativa de execução de uma operação não autorizada。
translation: 试图执行未经授权的操作

3:

试过:

DirectorySecurity security = Directory.GetAccessControl(dir.FullName);

与上述相同的例外。

4

2 回答 2

0

这似乎是一个很好的问题来发布我的SafeWalk课程,在这里收集来自多个答案的提示。它能够在我的盒子上遍历 C:\ 和 D:\ 而不会造成问题。

public static class SafeWalk {
    [Flags]
    public enum ReturnOptions {
        ReturnFiles = 1, ReturnDirectories = 2, ReturnBoth = 3
    }

    const string AllFiles = "*.*";

    // File and Directory Name Tree Walkers

    public static IEnumerable<string> SafeEnumerateFileAndDirNames(this DirectoryInfo di, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        di.FullName.SafeEnumerateFileAndDirNames(AllFiles, AllFiles, searchOpt, ReturnOptions.ReturnBoth);

    public static IEnumerable<string> SafeEnumerateFileAndDirNames(this DirectoryInfo di, string filePattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        di.FullName.SafeEnumerateFileAndDirNames(filePattern, AllFiles, searchOpt, ReturnOptions.ReturnBoth);

    public static IEnumerable<string> SafeEnumerateFileAndDirNames(this DirectoryInfo di, string filePattern, string dirPattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        di.FullName.SafeEnumerateFileAndDirNames(filePattern, dirPattern, searchOpt, ReturnOptions.ReturnBoth);

    public static IEnumerable<string> SafeEnumerateFileAndDirNames(this string path, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        path.SafeEnumerateFileAndDirNames(AllFiles, AllFiles, searchOpt, ReturnOptions.ReturnBoth);

    public static IEnumerable<string> SafeEnumerateFileAndDirNames(this string path, string filePattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        path.SafeEnumerateFileAndDirNames(filePattern, AllFiles, searchOpt, ReturnOptions.ReturnBoth);

    public static IEnumerable<string> SafeEnumerateFileAndDirNames(this string path, string filePattern, string dirPattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly, ReturnOptions returnOpt = ReturnOptions.ReturnBoth) {
        var searchQueue = new Queue<string>() { path };

        while (searchQueue.Count > 0) {
            var cdn = searchQueue.Dequeue();

            IEnumerable<string> cdiFiles = null;
            if (returnOpt.HasFlag(ReturnOptions.ReturnFiles)) {
                try {
                    cdiFiles = Directory.EnumerateFiles(cdn, filePattern, SearchOption.TopDirectoryOnly);
                }
                catch (Exception) {
                }

                if (cdiFiles != null)
                    foreach (var filename in cdiFiles)
                        yield return filename;
            }

            if ((!returnOpt.HasFlag(ReturnOptions.ReturnFiles) || cdiFiles != null) && (returnOpt.HasFlag(ReturnOptions.ReturnDirectories) || searchOpt == SearchOption.AllDirectories)) { // skip if file enumeration failed
                IEnumerable<string> cdiDirs = null;
                try {
                    cdiDirs = Directory.EnumerateDirectories(cdn, dirPattern, SearchOption.TopDirectoryOnly);
                }
                catch (Exception) {
                }

                if (cdiDirs != null) {
                    foreach (var dirname in cdiDirs) {
                        if (searchOpt == SearchOption.AllDirectories)
                            searchQueue.Enqueue(dirname);

                        if (returnOpt.HasFlag(ReturnOptions.ReturnDirectories))
                            yield return dirname;
                    }
                }
            }
        }
    }

    public static IEnumerable<string> SafeEnumerateFileNames(this string path, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        path.SafeEnumerateFileAndDirNames(AllFiles, AllFiles, searchOpt, ReturnOptions.ReturnFiles);

    public static IEnumerable<string> SafeEnumerateFileNames(this string path, string filePattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        path.SafeEnumerateFileAndDirNames(filePattern, AllFiles, searchOpt, ReturnOptions.ReturnFiles);

    public static IEnumerable<string> SafeEnumerateFileNames(this string path, string filePattern, string dirPattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        path.SafeEnumerateFileAndDirNames(filePattern, dirPattern, searchOpt, ReturnOptions.ReturnFiles);

    public static IEnumerable<string> SafeEnumerateFileNames(this DirectoryInfo path, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        path.FullName.SafeEnumerateFileAndDirNames(AllFiles, AllFiles, searchOpt, ReturnOptions.ReturnFiles);

    public static IEnumerable<string> SafeEnumerateFileNames(this DirectoryInfo path, string filePattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        path.FullName.SafeEnumerateFileAndDirNames(filePattern, AllFiles, searchOpt, ReturnOptions.ReturnFiles);

    public static IEnumerable<string> SafeEnumerateFileNames(this DirectoryInfo path, string filePattern, string dirPattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        path.FullName.SafeEnumerateFileAndDirNames(filePattern, dirPattern, searchOpt, ReturnOptions.ReturnFiles);

    public static IEnumerable<string> SafeEnumerateDirectoryNames(this string path, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        path.SafeEnumerateFileAndDirNames(AllFiles, AllFiles, searchOpt, ReturnOptions.ReturnDirectories);

    public static IEnumerable<string> SafeEnumerateDirectoryNames(this string path, string dirPattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        path.SafeEnumerateFileAndDirNames(AllFiles, dirPattern, searchOpt, ReturnOptions.ReturnDirectories);

    public static IEnumerable<string> SafeEnumerateDirectoryNames(this DirectoryInfo path, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        path.FullName.SafeEnumerateFileAndDirNames(AllFiles, AllFiles, searchOpt, ReturnOptions.ReturnDirectories);

    public static IEnumerable<string> SafeEnumerateDirectoryNames(this DirectoryInfo path, string dirPattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        path.FullName.SafeEnumerateFileAndDirNames(AllFiles, dirPattern, searchOpt, ReturnOptions.ReturnDirectories);

    // File and Directory Info Tree Walkers

    public static IEnumerable<FileSystemInfo> SafeEnumerateFileSystemInfos(this string path, SearchOption searchOpt = SearchOption.TopDirectoryOnly, ReturnOptions returnOpt = ReturnOptions.ReturnBoth) =>
        new DirectoryInfo(path).SafeEnumerateFileSystemInfos(AllFiles, AllFiles, searchOpt, returnOpt);

    public static IEnumerable<FileSystemInfo> SafeEnumerateFileSystemInfos(this string path, string searchPattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly, ReturnOptions returnOpt = ReturnOptions.ReturnBoth) =>
        new DirectoryInfo(path).SafeEnumerateFileSystemInfos(searchPattern, searchPattern, searchOpt, returnOpt);

    public static IEnumerable<FileSystemInfo> SafeEnumerateFileSystemInfos(this string path, string filePattern, string dirPattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly, ReturnOptions returnOpt = ReturnOptions.ReturnBoth) =>
        new DirectoryInfo(path).SafeEnumerateFileSystemInfos(filePattern, dirPattern, searchOpt, returnOpt);

    public static IEnumerable<FileSystemInfo> SafeEnumerateFileSystemInfos(this DirectoryInfo di, SearchOption searchOpt = SearchOption.TopDirectoryOnly, ReturnOptions returnOpt = ReturnOptions.ReturnBoth) =>
        di.SafeEnumerateFileSystemInfos(AllFiles, AllFiles, searchOpt, returnOpt);

    public static IEnumerable<FileSystemInfo> SafeEnumerateFileSystemInfos(this DirectoryInfo di, string searchPattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly, ReturnOptions returnOpt = ReturnOptions.ReturnBoth) =>
        di.SafeEnumerateFileSystemInfos(searchPattern, searchPattern, searchOpt, returnOpt);

    public static IEnumerable<FileSystemInfo> SafeEnumerateFileSystemInfos(this DirectoryInfo di, string filePattern, string dirPattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly, ReturnOptions returnOpt = ReturnOptions.ReturnBoth) {
        var searchQueue = new Queue<DirectoryInfo>();
        searchQueue.Enqueue(di);
        while (searchQueue.Count > 0) {
            var cdi = searchQueue.Dequeue();

            IEnumerable<string> cdiFiles = null;
            if (returnOpt.HasFlag(ReturnOptions.ReturnFiles)) {
                try {
                    cdiFiles = Directory.EnumerateFiles(cdi.FullName, filePattern, SearchOption.TopDirectoryOnly);
                }
                catch (Exception) {
                }

                if (cdiFiles != null) {
                    var cfis = new ConcurrentBag<FileInfo>();
                    cdiFiles.AsParallel()
                            .ForAll(f => {
                                try {
                                    cfis.Add(new FileInfo(f));
                                }
                                catch (Exception) {
                                }
                            });

                    foreach (var fi in cfis)
                        yield return fi;
                }
            }

            if ((!returnOpt.HasFlag(ReturnOptions.ReturnFiles) || cdiFiles != null) && (returnOpt.HasFlag(ReturnOptions.ReturnDirectories) || searchOpt.HasFlag(SearchOption.AllDirectories))) { // skip if file enumeration failed
                IEnumerable<string> cdiDirs = null;
                try {
                    cdiDirs = Directory.EnumerateDirectories(cdi.FullName, dirPattern, SearchOption.TopDirectoryOnly);
                }
                catch (Exception) {
                }

                if (cdiDirs != null) {
                    var cdis = new ConcurrentBag<DirectoryInfo>();
                    cdiDirs.AsParallel()
                           .ForAll(d => {
                               try {
                                   cdis.Add(new DirectoryInfo(d));
                               }
                               catch (Exception) {
                               }
                           });
                    foreach (var rdi in cdis) {
                        if (returnOpt.HasFlag(ReturnOptions.ReturnDirectories))
                            yield return rdi;
                        if (searchOpt == SearchOption.AllDirectories)
                            searchQueue.Enqueue(rdi);
                    }
                }
            }
        }
    }

    public static IEnumerable<FileInfo> SafeEnumerateFileInfos(this string path, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        new DirectoryInfo(path).SafeEnumerateFileSystemInfos(AllFiles, AllFiles, searchOpt, ReturnOptions.ReturnFiles).Cast<FileInfo>();

    public static IEnumerable<FileInfo> SafeEnumerateFileInfos(this string path, string filePattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        new DirectoryInfo(path).SafeEnumerateFileSystemInfos(filePattern, AllFiles, searchOpt, ReturnOptions.ReturnFiles).Cast<FileInfo>();

    public static IEnumerable<FileInfo> SafeEnumerateFileInfos(this string path, string filePattern, string dirPattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        new DirectoryInfo(path).SafeEnumerateFileSystemInfos(filePattern, dirPattern, searchOpt, ReturnOptions.ReturnFiles).Cast<FileInfo>();

    public static IEnumerable<FileInfo> SafeEnumerateFileInfos(this DirectoryInfo di, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        di.SafeEnumerateFileSystemInfos(AllFiles, AllFiles, searchOpt, ReturnOptions.ReturnFiles).Cast<FileInfo>();

    public static IEnumerable<FileInfo> SafeEnumerateFileInfos(this DirectoryInfo di, string filePattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        di.SafeEnumerateFileSystemInfos(filePattern, AllFiles, searchOpt, ReturnOptions.ReturnFiles).Cast<FileInfo>();

    public static IEnumerable<FileInfo> SafeEnumerateFileInfos(this DirectoryInfo di, string filePattern, string dirPattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        di.SafeEnumerateFileSystemInfos(filePattern, dirPattern, searchOpt, ReturnOptions.ReturnFiles).Cast<FileInfo>();

    public static IEnumerable<DirectoryInfo> SafeEnumerateDirectoryInfos(this string path, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        new DirectoryInfo(path).SafeEnumerateFileSystemInfos(AllFiles, AllFiles, searchOpt, ReturnOptions.ReturnDirectories).Cast<DirectoryInfo>();

    public static IEnumerable<DirectoryInfo> SafeEnumerateDirectoryInfos(this string path, string dirPattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        new DirectoryInfo(path).SafeEnumerateFileSystemInfos(AllFiles, dirPattern, searchOpt, ReturnOptions.ReturnDirectories).Cast<DirectoryInfo>();

    public static IEnumerable<DirectoryInfo> SafeEnumerateDirectoryInfos(this DirectoryInfo di, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        di.SafeEnumerateFileSystemInfos(AllFiles, AllFiles, searchOpt, ReturnOptions.ReturnDirectories).Cast<DirectoryInfo>();

    public static IEnumerable<DirectoryInfo> SafeEnumerateDirectoryInfos(this DirectoryInfo di, string dirPattern, SearchOption searchOpt = SearchOption.TopDirectoryOnly) =>
        di.SafeEnumerateFileSystemInfos(AllFiles, dirPattern, searchOpt, ReturnOptions.ReturnDirectories).Cast<DirectoryInfo>();
}
于 2020-02-12T21:27:31.573 回答
-1

如何在执行之前检查我是否有权枚举文件夹的内容?

你不能。或者至少不够可靠,无法与之结合。磁盘访问是您可以重新尝试的事情。仅仅因为它工作过一次,并不意味着它将继续工作。我的意思是,如果有人在这次读取和最后一次读取之间取出磁盘,你会怎么做?或者如果文件夹权限被更改?你必须期待的事情太多了。

磁盘错误属于Exogenous Exceptions类。而那些你只能处理,永远不会避免的。

至于正确的异常处理,我有两篇文章。我已经链接的第一个。第二个是这样的:https ://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET

于 2020-02-12T18:05:14.753 回答