As you know, it's easy to get a list of all the files and folders in the first level of a directory:
DirectoryInfo di=new DirectoryInfo (strbasedir);//strbasedir is the starting directory, absolute address
Directoryinfo[] Dia=di. GetDirectories ();//Get all sub-directories
Fileinfo[] Fia=di. GetFiles ();//Get all the files from the starting directory
What if you want to get all the files and directories (including all subdirectories) in a directory? Directory is a layer of layers, we can not predict the depth of a directory, only to obtain the parent node, it is possible to understand the child nodes, to solve this problem, only the concept of recursion.
So what is recursion? Please do not have C friends to read first, I am here to simply say my understanding: recursion is a method, in this method, again call itself this method, which describes the depth of the operation of a thing ...-no nonsense, look at the code:
PublicArrayList al=NewArrayList ();//I use ArrayList as a dynamic array, very useful Public voidGetalldirlist (stringStrbasedir) {DirectoryInfo di=NewDirectoryInfo (Strbasedir); Directoryinfo[] DiA=di. GetDirectories (); for(intI=0; i<dia.length;i++) {al. ADD (Dia[i]. FullName); //Dia[i]. FullName is the absolute address of a subdirectory and records it in ArrayListgetalldirlist (Dia[i]. FullName); //Note: recursion. People with logical thinking should be able to react.}}
Finally, how do I get all the directory information out of ArrayList? As follows:
for (int i=0; i<al. count;i++) {textbox1.appendtext (Al[i]. ToString ()+""); //TextBox1 is a container, copy my Code, notice to change your own container }
C # Recursive methods traverse directories and subdirectories