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 orAllDirectories
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<string> GetFiles(string path, string[] exclude, SearchOption searchOption = SearchOption.AllDirectories)
{
IEnumerable<string> files = Directory.EnumerateFiles(path, "*.*", searchOption);
var resultFiles = new List<string>();
if (exclude.Length > 0)
{
foreach (var filename in files)
{
string extension = Path.GetExtension(filename);
if (Array.IndexOf(exclude, Path.GetFileName(filename)) >= 0)
{
continue;
}
if (string.IsNullOrEmpty(extension) || Array.IndexOf(exclude, "*" + extension) < 0)
{
resultFiles.Add(filename);
}
}
}
return resultFiles;
}
EnumerateFiles
inside the true block of(exclude.Length > 0)
. There's no reason to fetch file names otherwise. Also your check could be((exclude != null) && (exclude.Length > 0))
. \$\endgroup\$exclude
has no elements, the result should be the same asEnumerateFiles
, so I can't move it inside the true block. I'll add the check againstnull
. \$\endgroup\$exclude
has no elements, thenresultFiles
, which was initialized anew List<string>
, is simply returned without referencing anything fromEnumerateFiles
. \$\endgroup\$