0

I try to use this code for deleting files that contain a specific string in all subfolders of c:\

void Delete()
{
    string rootFolderPath = @"C:\";
    string filesToDelete = @"*apple*.algo";   // Only delete files containing "apple" in their filenames
    string[] fileList = System.IO.SearchOption.AllDirectories(rootFolderPath, filesToDelete);
    foreach(string file in fileList)
    {
        System.Diagnostics.Debug.WriteLine(file + "will be deleted");
        System.IO.File.Delete(file);
    }
}
Peter B
  • 22,460
  • 5
  • 32
  • 69
tony
  • 1
  • 2
    ok you tried,... and what was the result? please provide a problem description. – Mong Zhu May 17 '23 at 09:00
  • 3
    You are using `SearchOption.AllDirectories` as if it were a **method**, but [`SearchOption`](https://learn.microsoft.com/en-us/dotnet/api/system.io.searchoption) is an enum type and so `SearchOption.AllDirectories` is an **enum value**. See my link for an example how to use it. – Peter B May 17 '23 at 09:03
  • 1
    actually you are missing the `Directory.GetFiles` call. In this call you would pass the enum value as the third parameter – Mong Zhu May 17 '23 at 09:07
  • 4
    As suggested, you need to call `GetFiles` or, better, `EnumerateFiles`. Note that, if you do that for the root C drive folder targeting .NET Framework then you will encounter an inaccessible folder and an exception will be thrown, so you'd have to write your own recursive file search. Targeting .NET Core, there is an overload that will allow you to ignore that inaccessible folder, so be sure to account for that. – jmcilhinney May 17 '23 at 09:33
  • Does this answer your question? [How to recursively list all the files in a directory in C#?](https://stackoverflow.com/questions/929276/how-to-recursively-list-all-the-files-in-a-directory-in-c) – Charlieface May 17 '23 at 11:01

0 Answers0