How to get files ending with particular extension

Hello Community,

I have a array with the extensions of the files I need in a folder/sub folders.
There would be 1 to 4 elements in the array, As of now its just 2

{".html",".css"}

The syntax which i used when I just wanted to get html files from the folder and subfolder was

Directory.GetFiles("D:\Desktop\Document\Sections","*.html",SearchOption.AllDirectories)

But now i want the files that end with both .html and .css.

Thank you

@hansen_Lobo

Assign filesWithExtensions = Directory.GetFiles(“D:\Desktop\Document\Sections”, “.”, SearchOption.AllDirectories).Where(Function(file) extensions.Contains(Path.GetExtension(file))).ToArray()

Then, we use the LINQ Where method to filter the file names based on whether their extensions exist in the extensions array. The Path.GetExtension function is used to extract the extension from each file name, and then we check if the extension exists in the extensions array using the Contains method.

(From f in GetFiles("D:\Desktop\Document\Sections","*.*",SearchOption.AllDirectories)
Let xt = Path.GetExtension(f).toUpper.Replace(".","")
Where {"HTML","CSS"}.Contains(xt)
Select fp = f).toArray

Taken and adapted from 🦉 🔖 [CheatSheet] - Filesystem APIs

It works.

Another question:

How do i use a variable name instead of hardcoding {“HTML”,“CSS”}

@hansen_Lobo

Then use this

Assign filesWithExtensions = Directory.GetFiles(“D:\Desktop\Document\Sections”, “.”, SearchOption.AllDirectories).Where(Function(file) file.ToLower().EndsWith(“.html”) Or file.ToLower().EndsWith(“.css”)).ToArray()

arrExtensions | String() = {“HTML”,“CSS”}

(From f in GetFiles("D:\Desktop\Document\Sections","*.*",SearchOption.AllDirectories)
Let xt = Path.GetExtension(f).toUpper.Replace(".","")
Where arrExtensions.Contains(xt)
Select fp = f).toArray

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.