Home > OS >  How to Recursively Delete the Files with Specific Extension
How to Recursively Delete the Files with Specific Extension

Time:12-20

I am using the Following Code to delete the Files with Specific extension

private void deleteFilesFromLocalDirectory() {
    DirectoryInfo di = new DirectoryInfo(@"Z:\Doku\Instructions\");
    FileInfo[] files = di.GetFiles("*.odt").Where(p => p.Extension == ".odt").ToArray();
    foreach (FileInfo file in files)
        try
        {
            file.Attributes = FileAttributes.Normal;
            File.Delete(file.FullName);
        }
        catch { }
}

I have many Folders inside the Instructions and I want my code to go to each and every folder inside the Instructions and delete the files with ".odt" extensions. Currently my code is only deleting the ".odt" files on the location which I am providing i.e. (Z:\Doku\Instructions)

i want my code to delete ".odt" Files from all the folders inside the Instructions

CodePudding user response:

It is always a good idea to check the documentation for the APIs you are using. You can use this overload to search all nested folders. And you don't need the Where clause since you are already specifying the extension.

string[] files = Directory.GetFiles("your path here", "*.odt", System.IO.SearchOptions.AllDirectories).ToArray();

You can also manually recurse through folders

CodePudding user response:

There is an overload of the Directory.GetFiles API that accepts an SearchOption that lets you specify that you want search the current dictionary and all its subdirectories.

It returns a string[] so you should modify your current a bit:

private void deleteFilesFromLocalDirectory()
{
    string[] files = Directory.GetFiles(@"Z:\Doku\Instructions\", "*.odt",
        System.IO.SearchOption.AllDirectories);
    foreach (string file in files)
        try
        {
            File.Delete(file);
        }
        catch { }
}
  • Related