Directory.EnumerateFiles => UnauthorizedAccessException

前端 未结 5 668
滥情空心
滥情空心 2020-11-27 03:42

There is a nice new method in .NET 4.0 for getting files in a directory in a streaming way via enumeration.

The problem here is that if one wishes to enumerate all f

5条回答
  •  没有蜡笔的小新
    2020-11-27 03:50

    Ths issue with the above answer is that is does not take care of exception in sub directories. This would be a better way to handling those exceptions so you get ALL files from ALL subdirectories except those with threw an access exception:

        /// 
        /// A safe way to get all the files in a directory and sub directory without crashing on UnauthorizedException or PathTooLongException
        /// 
        /// Starting directory
        /// Filename pattern match
        /// Search subdirectories or only top level directory for files
        /// List of files
        public static IEnumerable GetDirectoryFiles(string rootPath, string patternMatch, SearchOption searchOption)
        {
            var foundFiles = Enumerable.Empty();
    
            if (searchOption == SearchOption.AllDirectories)
            {
                try
                {
                    IEnumerable subDirs = Directory.EnumerateDirectories(rootPath);
                    foreach (string dir in subDirs)
                    {
                        foundFiles = foundFiles.Concat(GetDirectoryFiles(dir, patternMatch, searchOption)); // Add files in subdirectories recursively to the list
                    }
                }
                catch (UnauthorizedAccessException) { }
                catch (PathTooLongException) {}
            }
    
            try
            {
                foundFiles = foundFiles.Concat(Directory.EnumerateFiles(rootPath, patternMatch)); // Add files from the current directory
            }
            catch (UnauthorizedAccessException) { }
    
            return foundFiles;
        }
    

提交回复
热议问题