Recursive iteration in C #

I have a custom object that contains methods that return all the directory and file names in the root directory

string[] dirlist = obj.GetDirectories();

//which returns all dir names in root

string[] filelist = obj.GetFiles();

//which return all file names in root

I cannot change these methods. As soon as I get a darlist, how can I get a list of all the sub-files in it, as well as the files in the sub-folders, ignoring the security exceptions. It can be nested on several levels. Anything in .NET 4?

Update: the string [] dirList can also be read as a "List Disler". Please give a solution that uses the latest .NET features.

DirectoryOne  
 - SubDirOne  
 - SubDirTwo  
     - FileOne  
     - FileTwo
     - SubDirThree      
DirectoryTwo
DirectoryOne
+3
source share
2 answers

There are built-in .NET methods for this:

// get all files in folder and sub-folders
Directory.GetFiles(path, "*", SearchOption.AllDirectories);

// get all sub-directories
Directory.GetDirectories(path, "*", SearchOption.AllDirectories);

Somehow I feel that this is not the solution you are looking for, though.

Update: , , , LINQ. , , :

// get all files given a collection of directories as a string array
dirList.SelectMany(x => Directory.GetFiles(x, "*", SearchOption.AllDirectories));

// get all sub-directories given a collection of directories as a string array
dirList.SelectMany(x => x.Directory.GetDirectories(x, "*", SearchOption.AllDirectories));
+9

foreach(string dir in Directory.GetDirectories("c:\","",SearchOption.AllDirectories))
{
 Console.Writeline(dir);
 foreach(string file in Directory.GetFiles(dir))
 {
   Console.Writline(file);
 } 
}

C:\, . ?

0

Source: https://habr.com/ru/post/1788152/


All Articles