proggrock
proggrock

Reputation: 3289

Need advice on good way to filter out certain file names from Directory.GetFiles method in C#

In my MVC app I'm returning files from a file server into my view.

To simplify my problem: Let's say I have file1, file2, and file3 being returned from my Directory.GetFiles method. I've been instructed not to return file2, hence only showing file1 and file3 in my view.

Inevitably they'll come a time when rules change and file2 will need to be showed again. What would be the smartest way to keep a list of the currently filtered out files and check against that list? (without setting the files to "hidden"); One idea I could do is write the filename in a repository and cross check against it, but I'm just worried about creating a maintenance catastrophe...

is there a better solution im overlooking?

Upvotes: 1

Views: 212

Answers (2)

Yahia
Yahia

Reputation: 70369

try

var ForbiddenList = new string[] {"file2"};

var Result = Directory.GetFiles().Except (ForbiddenList);

EDIT - as per comment:

Caching the result can be achieved rather easily...

var FullList = Directory.GetFiles ();
var ForbiddenList = new string[] {"file2"};

Then you can choose what to display - when you need to display all then just use FullList, when you need to display only the existing forbidden Files you could FullList.Intersect (ForbiddenList) and when you need to display all without the forbidden files you do FullList.Except (ForbiddenList) .

Upvotes: 6

Lucero
Lucero

Reputation: 60190

I'd use a configurable regular expression to filter the files. This has several advantages: you can exclude any pattern (such as a specific extension, or files starting with a specific string, or multiple files), and it is easy to maintain (maybe even via a web frontend).

Upvotes: 2

Related Questions