Search code examples
c#directorygetfiles

Listing files in main directory and subdirectories


I currently have a code that scans a given directory for folders and lists everything into a listbox. However, I would also like to scan for files under each folder. I would like to use this code as it outputs a tree like folder structure. What do I need to add to my code to also get the files? Thanks!

private void ScanSelectedFolder(String prefix, String path)
{

    try
    {
        DirectoryInfo di = new DirectoryInfo(path);
        foreach (var dir in new DirectoryInfo(path).GetDirectories("*", SearchOption.TopDirectoryOnly))
        {
            listBox1.Invoke((MethodInvoker)delegate { 
                listBox1.Items.Add(prefix + dir.Name + " (" + dir.Name.Length.ToString() + ")   "); });
                ScanFolder(prefix + "―", dir.FullName);
            }
        }
        catch
        {
            if (!this.IsDisposed)
            {
                listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add("Access Denied to : " + path); });
            }
        }
    }
}

Output:

Radeon-Software-Adrenalin-18.3.3-MinimalSetup-180319_web (56)
―Bin (3)
――localization (12)
―――cs (2)
―――da_DK (5)
―――de (2)
―――el_GR (5)
―――es_ES (5)
―――fi_FI (5)
―――fr_FR (5)
―――hu_HU (5)
―――it_IT (5)
―――ja (2)
―――ko_KR (5)
―――nl_NL (5)
―――no (2)
―――pl (2)
―――pt_BR (5)
―――ru_RU (5)
―――sv_SE (5)
―――th (2)
―――tr_TR (5)
―――zh_CN (5)
―――zh_TW (5)
―Bin64 (5)
――localization (12)
―――cs (2)
―――da_DK (5)
―――de (2)
―――el_GR (5)
―――es_ES (5)
―――fi_FI (5)


Solution

  • Something like this:

    DirectoryInfo di = new DirectoryInfo(path);
    foreach (var dir in new DirectoryInfo(path).GetDirectories("*", SearchOption.TopDirectoryOnly))
    {
        listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(prefix + dir.Name + " (" + dir.Name.Length.ToString() + ")   "); });
    
        foreach (FileInfo fileInfo in dir.GetFiles())
        {
            listBox1.Invoke((MethodInvoker) delegate { listBox1.Items.Add(prefix + fileInfo.Name); });
        }
        ScanSelectedFolder(prefix + "―", dir.FullName);
    }