locked
How do I filter a List<FileInfo> to include only results whose extension 'EndsWith' extensions that are contained within a List<string> RRS feed

  • Question

  • User-1644933537 posted

    This is what I have so far, and it did work when hard coding a single extension, like PDF, but I also need to do the same for word documents (doc, docx, and any future word ext's)

    I just don't know how to tell the equation that any file that EndsWith an extension that is Contained within the List is OK.

    // the 'directoryPath' variable is just a string of the unc path to the targeted files
    // the 'filename' variable is a string of the file name less the extension.
    // the 'allowedExtList' variable is a List<string> that contains 'doc' and 'docx'
    // SplitFileName is just a simple method that splits the 'filename.ext' into 2 rows (file[0] and ext[1]), less the period.

    DirectoryInfo di = new DirectoryInfo(directoryPath);
    List<FileInfo> fiList = di.GetFiles(SplitFileName(fileName)[0] + "*").Where(x => x.Name.EndsWith("." + allowedExtList)).ToList<FileInfo>();

    Thanks for your time and suggestions.

    Saturday, November 8, 2014 8:43 PM

Answers

  • User-821857111 posted

    There a re built-in methods for handling this kind of thing. Path.GetExtension will return the file extension (with a dot). Likewise, you can get the extension from FileInfo.Extension. Here's an extension method on DirectoryInfo that does what you want:

    public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo directoryInfo, params string[] extensions) {
        var allowedExtensions = new HashSet<string>(extensions, StringComparer.OrdinalIgnoreCase);
        return directoryInfo.EnumerateFiles().Where(f => allowedExtensions.Contains(f.Extension));
    }

    You call it like this:

    var files = di.GetFilesByExtensions(".jpg", ".gif", ".png");
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, November 9, 2014 4:06 AM

All replies

  • User-821857111 posted

    There a re built-in methods for handling this kind of thing. Path.GetExtension will return the file extension (with a dot). Likewise, you can get the extension from FileInfo.Extension. Here's an extension method on DirectoryInfo that does what you want:

    public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo directoryInfo, params string[] extensions) {
        var allowedExtensions = new HashSet<string>(extensions, StringComparer.OrdinalIgnoreCase);
        return directoryInfo.EnumerateFiles().Where(f => allowedExtensions.Contains(f.Extension));
    }

    You call it like this:

    var files = di.GetFilesByExtensions(".jpg", ".gif", ".png");
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, November 9, 2014 4:06 AM
  • User-1644933537 posted

    Thanks Mike, I was able to modify your code to meet my needs,

    Sunday, November 9, 2014 3:55 PM