Removing specific files in a directory using C #

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

I use the following code to delete the entire .bmp file in my C: \ TEMP directory, but somehow it does not work as I expect. Can someone help me with this?

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

I have already verified that the .bmp file and directory do not have a read-only attribute

+6
source share
3 answers

To get started, GetFiles has an overload that accepts the search pattern http://msdn.microsoft.com/en-us/library/wz42302f.aspx , so you can do:

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

Change: 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);
    }

In this case, all .bmp files in the folder are deleted, but there is no access to subfolders.

+13
source

.EndsWith .Contains

+3

:

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

:

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

, .

-1

All Articles