kown owl
kown owl

Reputation: 43

Looking for folders in multiple extension and multiple string format

Hi I am trying to get all the files with a set of extension and a set of string format

string extensions=".exe,.txt,.xls";
string fileFormat"fileA, fileB, fileC";

let says if i have the following files in the folder

fileA20200805.txt
fileBxxxx.exe
FileCCCCCCC.txt
FileD123.xls

the result should only return the first 3 files which is

fileA20200805.txt
fileBxxxx.exe
FileCCCCCCC.txt 

because FileD123.xls is not in the fileFormat.

I have tried the following code:

Directoryinfo dInfo = new DirectoryInfo(path);
FileInfo[] files = dInfoGetFiles()
.Where(f => extensions.Contains(f.Extension.ToLower()) && fileFormat.Any(f.Name.Contains))
.ToArray();

However, I am still getting all 4 files, the FileD123.xls is still returning

Upvotes: 1

Views: 106

Answers (2)

Silny ToJa
Silny ToJa

Reputation: 2261

I think this should work.

string[] extensions = new string[] { ".exe",".txt",".xls" };
string[] fileFormat = new string[] { "fileA", "fileB", "fileC" };
DirectoryInfo dInfo = new DirectoryInfo(path);
FileInfo[] files = dInfo.GetFiles();
var output = files.Where(f => extensions.Contains(f.Extension.ToLower()) && 
fileFormat.Any(f.Name.Contains)).ToArray();

it return 2 because FileCCCCCCC dont equals fileC.

Upvotes: 1

TheGeneral
TheGeneral

Reputation: 81483

Maybe

var extensions = new [] {".exe",".txt",".xls"};
var fileFormat = new [] {"fileA", "fileB", "fileC"};


...


.Where(f => 
    extensions.Contains(f.Extension.ToLower()) && 
    fileFormat.Any(x => f.Name.StartsWith(x,  StringComparison.OrdinalIgnoreCase)))

You could also use regex i guess

var regex = new Regex(@$"({string.Join("|", fileFormat)}[^.]*({string.Join(" | ", extensions)})", RegexOptions.Compiled|RegexOptions.IgnoreCase);

...

.Where(f => regex.IsMatch(f.Name))

Upvotes: 2

Related Questions