Delete specific files in directory using C#

For starters, GetFiles has an overload which takes a search pattern http://msdn.microsoft.com/en-us/library/wz42302f.aspx so you can do:

Directory.GetFiles(@"C:\TEMP\", "*.bmp");

Edit: For the case of deleting all .bmp files in TEMP:

string[] filePaths = Directory.GetFiles(@"c:\TEMP\", "*.bmp");
foreach (string filePath in filePaths)
    {
        File.Delete(filePath);
    }

This deletes all .bmp files in the folder but does not access subfolders.


Should also use .EndsWith instead of .Contains

Tags:

C#