DirectoryInfo - DeleteFilesWhere

A DirectoryInfo extension method that deletes the files where.

Try it

public static string DirectoryName = "Main Directory";

public static void Main()
{
	CreateFilesAndDirectories();
	
	//C# Extension Method - DirectoryInfo - GetFileSystemEntries
	var entries = DirectoryName.ToDirectoryInfo().GetFileSystemEntries();

    foreach (var entry in entries)
    {
         Console.WriteLine(entry);
    }
	
	//C# Extension Method - DirectoryInfo - DeleteFilesWhere
	DirectoryName.ToDirectoryInfo().DeleteFilesWhere(x => x.Name.Contains("Framework"));
	
	Console.WriteLine("\n\nData in current directory after calling DeleteFilesWhere method.\n\n");

	//C# Extension Method - DirectoryInfo - GetFileSystemEntries
	entries = DirectoryName.ToDirectoryInfo().GetFileSystemEntries();
	
    foreach (var entry in entries)
    {
         Console.WriteLine(entry);
    }
}

private static void CreateFilesAndDirectories()
{
	DirectoryName.ToDirectoryInfo().Create();
	DirectoryName.ToDirectoryInfo().CreateSubdirectory("Entity Framework");
	DirectoryName.ToDirectoryInfo().CreateSubdirectory(".Net Framework");
	DirectoryName.ToDirectoryInfo().CreateSubdirectory("Java");
	DirectoryName.ToDirectoryInfo().CreateSubdirectory("SQL");
	string file1 = DirectoryName + "\\EntityFramework.txt";
    string file2 = DirectoryName + "\\oldTest.txt";
    file1.ToFileInfo().WriteAllText("EF text");
    file2.ToFileInfo().WriteAllText("text");
}

View Source
using System;
using System.IO;
using System.Linq;

public static partial class Extensions
{
    /// <summary>
    ///     A DirectoryInfo extension method that deletes the files where.
    /// </summary>
    /// <param name="obj">The obj to act on.</param>
    /// <param name="predicate">The predicate.</param>
    public static void DeleteFilesWhere(this DirectoryInfo obj, Func<FileInfo, bool> predicate)
    {
        obj.GetFiles().Where(predicate).ForEach(x => x.Delete());
    }

    /// <summary>
    ///     A DirectoryInfo extension method that deletes the files where.
    /// </summary>
    /// <param name="obj">The obj to act on.</param>
    /// <param name="searchOption">The search option.</param>
    /// <param name="predicate">The predicate.</param>
    public static void DeleteFilesWhere(this DirectoryInfo obj, SearchOption searchOption, Func<FileInfo, bool> predicate)
    {
        obj.GetFiles("*.*", searchOption).Where(predicate).ForEach(x => x.Delete());
    }
}