Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete specific files in directory using C#

Tags:

c#

There are many .bmp files present in my C:\TEMP directory.

I am using following code to delete all .bmp file in my C:\TEMP directory but somehow its not working as I expect. Can anyone help me in this?

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

I have already checked that .bmp file and the directory has no read only attribute

like image 884
Hiren Avatar asked Apr 12 '11 19:04

Hiren


2 Answers

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.

like image 167
Matt Lacey Avatar answered Nov 04 '22 01:11

Matt Lacey


Should also use .EndsWith instead of .Contains

like image 3
Chuck Savage Avatar answered Nov 04 '22 03:11

Chuck Savage