Get list of files in directory with exclude option This method returns the list of files (absolute path) in a folder (or tree). It allows filtering by extensions or filenames.

The method receives the following parameters:


string path: folder path to scan for files.
string[] exclude: can contain filenames such as "read.me" or extensions such as "*.jpg".
SearchOption searchOption: TopDirectoryOnly to scan only the specified folder or AllDirectories to scan tree folder under the specified path.


The method return files that doesn't appear in exclude array and a) hasn't extension, or b) extension doesn't appear in exclude array.



    public static IEnumerable&lt;string&gt; GetFiles(string path, string[] exclude, SearchOption searchOption = SearchOption.AllDirectories)
    {
        IEnumerable&lt;string&gt; files = Directory.EnumerateFiles(path, "*.*", searchOption);
        var resultFiles = new List&lt;string&gt;();

        if (exclude.Length &gt; 0)
        {
            foreach (var filename in files)
            {
                string extension = Path.GetExtension(filename);

                if (Array.IndexOf(exclude, Path.GetFileName(filename)) &gt;= 0)
                {
                    continue;
                }

                if (string.IsNullOrEmpty(extension) || Array.IndexOf(exclude, "*" + extension) &lt; 0)
                {
                    resultFiles.Add(filename);
                }
            }
        }

        return resultFiles;
    }
A few things I noticed:


If the exclude array is empty you return an empty list instead of every file.
reversing your logic would allow you to check everything in one statement.
Since you're returning an IEnumerable&lt;string&gt; already, using the yield operator would make sense here.
Accepting an IEnumerable&lt;string&gt; instead of an string[] for the exclude parameter, gives the user more options.  Also this allows you to leverage the LINQ extensions better.


Your code could look something like this:

public static IEnumerable&lt;string&gt; GetFiles(string path, IEnumerable&lt;string&gt; exclude, SearchOption searchOption = SearchOption.AllDirectories)
{
    IEnumerable&lt;FileInfo&gt; files = new DirectoryInfo(path).EnumerateFiles("*.*", searchOption);
    foreach (var filename in files)
    {

        if (!exclude.Any(x =&gt; x == filename.Name || (x.StartsWith("*") &amp;&amp; x.Contains(filename.Extension))))
        {
            yield return filename.Name;
        }

    }
}