Console App Task 14: How to filter files in a single step using Directory.EnumerateFiles() with LINQ in C# ?
Yes! You can filter files in a single step using Directory.EnumerateFiles()
with LINQ. This avoids unnecessary file retrievals and makes the code more efficient.
✅ Get Filtered Files in One Step
using System;
using System.IO;
using System.Linq;
class Program
{
static void Main()
{
string destinationPath = @"C:\YourFolderPath"; // Change this to your folder path
DateTime someMonthAgo = DateTime.Now.AddMonths(-3); // 3 months ago
// Get filtered files in one step
var filteredFiles = Directory.EnumerateFiles(destinationPath)
.Where(file => File.GetLastWriteTime(file) <= someMonthAgo && // Older than 3 months
(file.Contains("TS") || file.Contains("ECU"))) // Contains "TS" or "ECU"
.ToList();
// Print the filtered files
Console.WriteLine("Filtered Files:");
foreach (var file in filteredFiles)
{
Console.WriteLine(file);
}
}
}
📌 Why is This Better?
✅ Single Step Filtering → No need to store all files first, saves memory.
✅ Efficient → Uses Directory.EnumerateFiles()
, which reads files one at a time instead of loading everything at once.
✅ Flexible → Filters both date & name together.
If you like comment and share. 🚀
0 Comments