S
S
Segio2019-03-16 15:45:09
C++ / C#
Segio, 2019-03-16 15:45:09

How to order the output in the console?

You need to display all files and folders.

class Program
    {
        public static void Show(string dirPath)
        {
            DirectoryInfo dir = new DirectoryInfo(dirPath);
            //Папки
            string[] dirs = Directory.GetDirectories(dirPath);
            //Файлы
            FileInfo[] dirFiles = dir.GetFiles();
 
            for (int i = 0; i < dirFiles.Length; i++)
            {
                Console.WriteLine("     " + dirFiles[i]);                
            }
            for (int i = 0; i < dirs.Length; i++)
            {
                Console.WriteLine(dirs[i]);
                Show(dirs[i]);                
            }           
        }
        static void Main(string[] args)
        {
            Show("D:\\test");
            Console.ReadLine();
        }
    }

It seems to work. But how do you make nested folders with their contents indented? To visually see their nesting.
For example, in the folder test2 there is a folder test1 with its files. But they are all on the same level.
5c8cef8b13a27766448034.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
#
#, 2019-03-16
@mindtester

public static void Show(string dirPath, int level)
{
...
       var sb = new StringBuilder();
       sb.Append('\t', level);
       sb.Append(dirFiles[i]);
       Console.WriteLine(sb);
...
       Show(dirs[i], level + 1);
...
}
...
static void Main(string[] args)
{
       Show("D:\\test", 0);
...
}

ps Of course, other perversions are possible ..
spoiler
public static int level;
...
public static void Show(string dirPath)
{
...
       var sb = new StringBuilder();
       sb.Append('\t', level);
       sb.Append(dirFiles[i]);
       Console.WriteLine(sb);
...
       level++;
       Show(dirs[i]);
       level--;
       // очевидно что первый вариант будет попроще и понадежнее
...
}
...
static void Main(string[] args)
{
       level = 0;
       Show("D:\\test");
...
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question