Thursday 12 December 2019

C#.NET - Get All Files from the Directory with File Types Filter

The below code snippet will load all files from the given directory and filter the files by the given file type filter and returns the files info.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

public class FileProcessor
{
    /// <summary>
    /// Loads files by given filter
    /// </summary>
    /// <param name="directoryPath"></param>
    /// <param name="fileTypes"></param>
    /// <param name="caseSensitive"></param>
    /// <returns></returns>
    public IEnumerable<string> LoadFilesByFilters(string directoryPath, string[] fileTypes, bool caseSensitive = false)
    {
        StringComparer compare = StringComparer.OrdinalIgnoreCase;

        if (caseSensitive)
        {
            compare = StringComparer.Ordinal;
        }

        return Directory.EnumerateFiles(directoryPath, "*.*", SearchOption.TopDirectoryOnly)
                    .Where(file => fileTypes.Contains(Path.GetExtension(file), compare));
    }

    /// <summary>
    ///  How to Use?
    /// </summary>
    public IEnumerable<string> LoadFiles()
    {
        return LoadFilesByFilters(@"C:\Users\sravilla\Desktop\Repository", new[] { "*.xls", "*.xlsx" });
    }

}

No comments: