Need to create a directory tree. Suppose it is clear how to view all the files in the directory and all the folders, and how, after viewing all this, go to the directory above or below?

string path = Directory.GetCurrentDirectory(); string[] files = Directory.GetFiles(path); string[] directory = Directory.GetDirectories(path); for (int i = 0; i < 10; i++) { label2.Text = label2.Text + files[i].ToString() + "\r\n"; } for (int j = 0; j < 10; j++) { label3.Text = label3.Text + directory[j].ToString() + "\r\n"; } 

I'm not sure that I’m doing all this right, but as I know. And another question: how to determine the number of files or folders in a directory to register it in the condition?

1 answer 1

Go below you can get a list of folders in the current directory, which you have done ( Directory.GetDirectories() ).

You can go higher using the DirectoryInfo.Parent property:

 string path = Directory.GetCurrentDirectory(); var info = new DirectoryInfo(path); Console.WriteLine(info.Parent?.Name ?? "this is a root directory"); 

However, when building a directory tree, the transition to the directory above you do not need it. Enough to crawl down. An example of a recursion traversal:

 public void DirSearch(string path) { try { foreach (string d in Directory.GetDirectories(path)) { foreach (string f in Directory.GetFiles(d)) { Console.WriteLine(f); } DirSearch(d); } } catch (Exception e) { Console.WriteLine(e.Message); } } ... string path = Directory.GetCurrentDirectory(); DirSearch(path);