6

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

2
  • 3
    Tip: Use the searchPattern argument in Directory.GetFiles to only get bitmaps. (e.g. "*.bmp") See MSDN article Commented Apr 12, 2011 at 19:22
  • 1
    Are you running app manually under your user account, do you have access to delete files from C:\Temp? Also, are any of the files in use when your trying to delete them. What type of results / errors are you seeing when you try to delete the files ? Commented Apr 12, 2011 at 19:23

3 Answers 3

14

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.

Sign up to request clarification or add additional context in comments.

Comments

3

Should also use .EndsWith instead of .Contains

Comments

-1

You Could write below code in fast way:

 string[] t = Directory.GetFiles(Environment.CurrentDirectory, "*.pdf"); Array.ForEach(t, File.Delete); 

or For Text Files:

 string[] t = Directory.GetFiles(Environment.CurrentDirectory, "*.txt"); Array.ForEach(t, File.Delete); 

So, You could write code for all extension and all directories.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.