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

前端 未结 20 2330
名媛妹妹
名媛妹妹 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:40
    var filteredFiles = Directory
        .GetFiles(path, "*.*")
        .Where(file => file.ToLower().EndsWith("aspx") || file.ToLower().EndsWith("ascx"))
        .ToList();
    

    Edit 2014-07-23

    You can do this in .NET 4.5 for a faster enumeration:

    var filteredFiles = Directory
        .EnumerateFiles(path) //<--- .NET 4.5
        .Where(file => file.ToLower().EndsWith("aspx") || file.ToLower().EndsWith("ascx"))
        .ToList();
    

    Directory.EnumerateFiles in MSDN

    0 讨论(0)
  • 2020-11-27 11:43

    Just would like to say that if you use FileIO.FileSystem.GetFiles instead of Directory.GetFiles, it will allow an array of wildcards.

    For example:

    Dim wildcards As String() = {"*.html", "*.zip"}
    Dim ListFiles As List(Of String) = FileIO.FileSystem.GetFiles(directoryyouneed, FileIO.SearchOption.SearchTopLevelOnly, wildcards).ToList
    
    0 讨论(0)
  • 2020-11-27 11:45

    I like this method, because it is readable and avoids multiple iterations of the directory:

    var allowedExtensions = new [] {".doc", ".docx", ".pdf", ".ppt", ".pptx", ".xls", ".xslx"}; 
    var files = Directory
        .GetFiles(folder)
        .Where(file => allowedExtensions.Any(file.ToLower().EndsWith))
        .ToList();
    
    0 讨论(0)
  • 2020-11-27 11:48

    Instead of the EndsWith function, I would choose to use the Path.GetExtension() method instead. Here is the full example:

    var filteredFiles = Directory.EnumerateFiles( path )
    .Where(
        file => Path.GetExtension(file).Equals( ".aspx", StringComparison.OrdinalIgnoreCase ) ||
                Path.GetExtension(file).Equals( ".ascx", StringComparison.OrdinalIgnoreCase ) );
    

    or:

    var filteredFiles = Directory.EnumerateFiles(path)
    .Where(
        file => string.Equals( Path.GetExtension(file), ".aspx", StringComparison.OrdinalIgnoreCase ) ||
                string.Equals( Path.GetExtension(file), ".ascx", StringComparison.OrdinalIgnoreCase ) );
    

    (Use StringComparison.OrdinalIgnoreCase if you care about performance: MSDN string comparisons)

    0 讨论(0)
  • 2020-11-27 11:49

    I would try to specify something like

    var searchPattern = "as?x";
    

    it should work.

    0 讨论(0)
  • 2020-11-27 11:50

    I fear you will have to do somthing like this, I mutated the regex from here.

    var searchPattern = new Regex(
        @"$(?<=\.(aspx|ascx))", 
        RegexOptions.IgnoreCase);
    var files = Directory.EnumerateFiles(path)
        .Where(f => searchPattern.IsMatch(f))
        .ToList();
    
    0 讨论(0)
提交回复
热议问题