Multiple file-extensions searchPattern for System.IO.Directory.GetFiles

前端 未结 20 2327
名媛妹妹
名媛妹妹 2020-11-27 11:08

What is the syntax for setting multiple file-extensions as searchPattern on Directory.GetFiles()? For example filtering out files

相关标签:
20条回答
  • 2020-11-27 11:50
        /// <summary>
        /// Returns the names of files in a specified directories that match the specified patterns using LINQ
        /// </summary>
        /// <param name="srcDirs">The directories to seach</param>
        /// <param name="searchPatterns">the list of search patterns</param>
        /// <param name="searchOption"></param>
        /// <returns>The list of files that match the specified pattern</returns>
        public static string[] GetFilesUsingLINQ(string[] srcDirs,
             string[] searchPatterns,
             SearchOption searchOption = SearchOption.AllDirectories)
        {
            var r = from dir in srcDirs
                    from searchPattern in searchPatterns
                    from f in Directory.GetFiles(dir, searchPattern, searchOption)
                    select f;
    
            return r.ToArray();
        }
    
    0 讨论(0)
  • 2020-11-27 11:53
    var filteredFiles = Directory
        .EnumerateFiles(path, "*.*") // .NET4 better than `GetFiles`
        .Where(
            // ignorecase faster than tolower...
            file => file.ToLower().EndsWith("aspx")
            || file.EndsWith("ascx", StringComparison.OrdinalIgnoreCase))
        .ToList();
    
    • Don't forget the new .NET4 Directory.EnumerateFiles for a performance boost (What is the difference between Directory.EnumerateFiles vs Directory.GetFiles?)
    • "IgnoreCase" should be faster than "ToLower"

    Or, it may be faster to split and merge your globs (at least it looks cleaner):

    "*.ext1;*.ext2".Split(';')
        .SelectMany(g => Directory.EnumerateFiles(path, g))
        .ToList();
    
    0 讨论(0)
  • 2020-11-27 11:53

    The easy-to-remember, lazy and perhaps imperfect solution:

    Directory.GetFiles(dir, "*.dll").Union(Directory.GetFiles(dir, "*.exe"))
    
    0 讨论(0)
  • 2020-11-27 11:53
        public static bool CheckFiles(string pathA, string pathB)
        {
            string[] extantionFormat = new string[] { ".war", ".pkg" };
            return CheckFiles(pathA, pathB, extantionFormat);
        }
        public static bool CheckFiles(string pathA, string pathB, string[] extantionFormat)
        {
            System.IO.DirectoryInfo dir1 = new System.IO.DirectoryInfo(pathA);
            System.IO.DirectoryInfo dir2 = new System.IO.DirectoryInfo(pathB);
            // Take a snapshot of the file system. list1/2 will contain only WAR or PKG 
            // files
            // fileInfosA will contain all of files under path directories 
            FileInfo[] fileInfosA = dir1.GetFiles("*.*", 
                                  System.IO.SearchOption.AllDirectories);
            // list will contain all of files that have ..extantion[]  
            // Run on all extantion in extantion array and compare them by lower case to 
            // the file item extantion ...
            List<System.IO.FileInfo> list1 = (from extItem in extantionFormat
                                              from fileItem in fileInfosA
                                              where extItem.ToLower().Equals 
                                              (fileItem.Extension.ToLower())
                                              select fileItem).ToList();
            // Take a snapshot of the file system. list1/2 will contain only WAR or  
            // PKG files
            // fileInfosA will contain all of files under path directories 
            FileInfo[] fileInfosB = dir2.GetFiles("*.*", 
                                           System.IO.SearchOption.AllDirectories);
            // list will contain all of files that have ..extantion[]  
            // Run on all extantion in extantion array and compare them by lower case to 
            // the file item extantion ...
            List<System.IO.FileInfo> list2 = (from extItem in extantionFormat
                                              from fileItem in fileInfosB
                                              where extItem.ToLower().Equals            
                                              (fileItem.Extension.ToLower())
                                              select fileItem).ToList();
            FileCompare myFileCompare = new FileCompare();
            // This query determines whether the two folders contain 
            // identical file lists, based on the custom file comparer 
            // that is defined in the FileCompare class. 
            return list1.SequenceEqual(list2, myFileCompare);
        }
    
    0 讨论(0)
  • 2020-11-27 11:54

    A more efficient way of getting files with the extensions ".aspx" and ".ascx" that avoids querying the file system several times and avoids returning a lot of undesired files, is to pre-filter the files by using an approximate search pattern and to refine the result afterwards:

    var filteredFiles = Directory.GetFiles(path, "*.as?x")
        .Select(f => f.ToLowerInvariant())
        .Where(f => f.EndsWith("px") || f.EndsWith("cx"))
        .ToList();
    
    0 讨论(0)
  • 2020-11-27 11:57

    c# version of @qfactor77's answer. This is the best way without LINQ .

    string[] wildcards= {"*.mp4", "*.jpg"};
    ReadOnlyCollection<string> filePathCollection = FileSystem.GetFiles(dirPath, Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, wildcards);
    string[] filePath=new string[filePathCollection.Count];
    filePathCollection.CopyTo(filePath,0);
    

    now return filePath string array. In the beginning you need

    using Microsoft.VisualBasic.FileIO;
    using System.Collections.ObjectModel;
    

    also you need to add reference to Microsoft.VisualBasic

    0 讨论(0)
提交回复
热议问题