Looking for folders in multiple extension and multiple string format

大城市里の小女人 提交于 2021-01-27 18:58:51

问题


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


回答1:


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.




回答2:


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))


来源:https://stackoverflow.com/questions/63262750/looking-for-folders-in-multiple-extension-and-multiple-string-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!