Esempio n. 1
0
        /// <summary>
        /// Gets files from the specified directory using globbing patterns.
        /// </summary>
        /// <param name="directory">The directory to search.</param>
        /// <param name="patterns">The globbing pattern(s) to use.</param>
        /// <returns>Files that match the globbing pattern(s).</returns>
        public static IEnumerable <FileInfo> GetFiles(DirectoryInfo directory, IEnumerable <string> patterns)
        {
            // Initially based on code from Reliak.FileSystemGlobbingExtensions (https://github.com/reliak/Reliak.FileSystemGlobbingExtensions)

            var matcher = new Matcher(StringComparison.OrdinalIgnoreCase);

            // Expand braces
            var expandedPatterns = patterns
                                   .SelectMany(ExpandBraces)
                                   .Select(f => f.Replace("\\{", "{").Replace("\\}", "}")); // Unescape braces

            // Add the patterns, any that start with ! are exclusions
            foreach (var expandedPattern in expandedPatterns)
            {
                var isExclude    = expandedPattern[0] == '!';
                var finalPattern = isExclude ? expandedPattern.Substring(1) : expandedPattern;
                finalPattern = finalPattern
                               .Replace("\\!", "!") // Unescape negation
                               .Replace("\\", "/"); // Normalize slashes

                // No support for absolute paths
                if (System.IO.Path.IsPathRooted(finalPattern))
                {
                    throw new ArgumentException($"Rooted globbing patterns are not supported ({expandedPattern})", nameof(patterns));
                }

                // Add exclude or include pattern to matcher
                if (isExclude)
                {
                    matcher.AddExclude(finalPattern);
                }
                else
                {
                    matcher.AddInclude(finalPattern);
                }
            }

            DirectoryInfoBase directoryInfo = new DirectoryInfoWrapper(directory);
            var result = matcher.Execute(directoryInfo);

            return(result.Files.Select(match => directoryInfo.GetFile(match.Path)).Select(fb => new FileInfo(fb.FullName)));
        }