My code has a function that scans a root directory and showing txt files (for example) in a TreeView:
private TreeNode DirectoryToTreeView(TreeNode parentNode, string path,
                                     string extension = ".txt")
{
    var result = new TreeNode(parentNode == null ? path : Path.GetFileName(path));
    foreach (var dir in Directory.GetDirectories(path))
    {
        TreeNode node = DirectoryToTreeView(result, dir);
        if (node.Nodes.Count > 0)
        {
            result.Nodes.Add(node);
        }
    }
    foreach (var file in Directory.GetFiles(path))
    {
        if (Path.GetExtension(file).ToLower() == extension.ToLower())
        {
            result.Nodes.Add(Path.GetFileName(file));
        }
    }
    return result;
}
This function should by called from the button like:
treeView1.Nodes.Add(DirectoryToTreeView(null, @"C:\Users\Tomer\Desktop\a"));
Its obviously freezing the UI.
I am new to this and I have searched the web and nothing seemed relevant to my problem because no one used recursive function and I cant simply call BeginInvoke on the entire function because it will have no effect.
What path should I take? Maybe change the function to work with a while loop and then calling BeginInvoke inside the if statements? Creating a TreeNode object in memory to populate (which may be too large)?
 
     
    