C# read folder (names) from directory
Asked Answered
C

2

9

I have this code:

        string directory;
        FolderBrowserDialog fbd = new FolderBrowserDialog();
        if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            directory = fbd.SelectedPath;

            txtSource.Text = directory;

            DirectoryInfo d = new DirectoryInfo(directory);
            FileInfo[] Files = d.GetFiles();

            List<String> str = new List<string>();
            foreach (FileInfo file in Files)
            {
                str.Add(file.Name);
            }
        }

I have a FolderBrowseDialog where I select the Path of the folder. In this selected folder are 3 other folders. I want to read out the names of these folders. I dont want to know or read out the names of files.

Charleton answered 30/6, 2016 at 12:31 Comment(0)
M
20

You can use Directory.GetDirectories():

string[] subdirs = Directory.GetDirectories(fbd.SelectedPath);

This gives you the full paths to the subdirectories. If you only need the names of the subfolders, but not the full path, you can use Path.GetFileName():

string[] subdirs = Directory.GetDirectories(fbd.SelectedPath)
                            .Select(Path.GetFileName)
                            .ToArray();

Or if you want both:

var subdirs = Directory.GetDirectories(fbd.SelectedPath)
                            .Select(p => new {
                                Path = p,
                                Name = Path.GetFileName(p)})
                            .ToArray();
Marvelous answered 30/6, 2016 at 12:33 Comment(1)
Ok then I have the path, how can i get the path and the name?Charleton
A
5

You need to use DirectoryInfo.GetDirectories.

using System;
using System.IO;

public class GetDirectoriesTest 
{
    public static void Main() 
    {

        // Make a reference to a directory.
        DirectoryInfo di = new DirectoryInfo("c:\\");

        // Get a reference to each directory in that directory.
        DirectoryInfo[] diArr = di.GetDirectories();

        // Display the names of the directories.
        foreach (DirectoryInfo dri in diArr)
            Console.WriteLine(dri.Name);
    }
}
Adamis answered 30/6, 2016 at 12:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.