[Solved] get tree structure of a directory with its subfolders and files using C#.net in windows application [closed]


Method 1

HierarchicalItem holds the information we need about an item in the folder. An item can be a folder or file.

class HierarchicalItem
{
    public string Name;
    public int Deepth;

    public HierarchicalItem(string name, int deepth)
    {
        this.Name = name;
        this.Deepth = deepth;
    }
}

SearchDirectory is the recursive function to convert and flatten the tree structure to a list

    static IEnumerable<HierarchicalItem> SearchDirectory(DirectoryInfo directory, int deep = 0)
    {
        yield return new HierarchicalItem(directory.Name, deep);

        foreach (var subdirectory in directory.GetDirectories())
            foreach (var item in SearchDirectory(subdirectory , deep + 1))
                yield return item;

        foreach (var file in directory.GetFiles())
            yield return new HierarchicalItem(file.Name, deep + 1);
    }

Example :

        //fake TextBox...
        var textBox1 = new { Text = @"D:\Code\C#" };
        var directory = new DirectoryInfo(textBox1.Text);

        var items = SearchDirectory(directory);

        //you can print it to a console
        foreach (var item in items)
            Console.WriteLine(string.Concat(Enumerable.Repeat('\t', item.Deepth)) + item.Name);

        //or a textbox
        textBox1.Text = string.Join("\n", items.Select(i =>
            string.Concat(Enumerable.Repeat('\t', i.Deepth)) + i.Name));

        //or a table
        for (int i = 0; i < items.Count(); i++)
        {
            //with row = i, and column = items[i].Deepth + 1
        }

Method 2

This recursive method prints the directory like the tree command in CommandLine

    static string ScanFolder(DirectoryInfo directory, string indentation = "\t", int maxLevel = -1, int deep = 0)
    {
        StringBuilder builder = new StringBuilder();

        builder.AppendLine(string.Concat(Enumerable.Repeat(indentation, deep)) + directory.Name);

        if (maxLevel == -1 || maxLevel < deep)
        {
            foreach (var subdirectory in directory.GetDirectories())
                builder.Append(ScanFolder(subdirectory, indentation, maxLevel, deep + 1));
        }

        foreach (var file in directory.GetFiles())
            builder.AppendLine(string.Concat(Enumerable.Repeat(indentation, deep + 1)) + file.Name);

        return builder.ToString();
    }

solved get tree structure of a directory with its subfolders and files using C#.net in windows application [closed]