如何列出目录中的所有子目录

时间:2011-09-04 01:52:35

标签: c# directory

我正在开发一个项目,我需要列出目录中的所有子目录,例如我如何列出c:\

中的所有子目录

6 个答案:

答案 0 :(得分:109)

使用Directory.GetDirectories获取“your_directory_path”指定的目录的子目录。结果是一个字符串数组。

var directories = Directory.GetDirectories("your_directory_path");

默认情况下,只返回一级深度的子​​目录。可以选择以递归方式返回所有内容并过滤结果documented here,并在Clive的答案中显示。


避免UnauthorizedAccessException

如果你点击了一个你无权访问的目录,很容易得到UnauthorizedAccessException

您可能必须创建自己的方法来处理异常,如下所示:

public class CustomSearcher
{ 
    public static List<string> GetDirectories(string path, string searchPattern = "*",
        SearchOption searchOption = SearchOption.TopDirectoryOnly)
    {
        if (searchOption == SearchOption.TopDirectoryOnly)
            return Directory.GetDirectories(path, searchPattern).ToList();

        var directories = new List<string>(GetDirectories(path, searchPattern));

        for (var i = 0; i < directories.Count; i++)
            directories.AddRange(GetDirectories(directories[i], searchPattern));

        return directories;
    }

    private static List<string> GetDirectories(string path, string searchPattern)
    {
        try
        {
            return Directory.GetDirectories(path, searchPattern).ToList();
        }
        catch (UnauthorizedAccessException)
        {
            return new List<string>();
        }
    }
}

然后像这样称呼它:

var directories = CustomSearcher.GetDirectories("your_directory_path");

答案 1 :(得分:48)

这很简单:

string[] folders = System.IO.Directory.GetDirectories(@"C:\My Sample Path\","*", System.IO.SearchOption.AllDirectories);

答案 2 :(得分:6)

FolderBrowserDialog fbd = new FolderBrowserDialog();

        DialogResult result = fbd.ShowDialog();

        string[] files = Directory.GetFiles(fbd.SelectedPath);
        string[] dirs = Directory.GetDirectories(fbd.SelectedPath);

        foreach (string item2 in dirs)
        {
            FileInfo f = new FileInfo(item2);

            listBox1.Items.Add(f.Name);

        }

        foreach (string item in files)
        {
            FileInfo f = new FileInfo(item);

            listBox1.Items.Add(f.Name);

        }

答案 3 :(得分:5)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TRIAL
{
    public class Class1
    {
        static void Main(string[] args)
        {
           string[] fileArray = Directory.GetDirectories("YOUR PATH");
           for (int i = 0; i < fileArray.Length; i++)
           {

               Console.WriteLine(fileArray[i]);
           }
            Console.ReadLine();
        }
    }
}

答案 4 :(得分:0)

显示所有目录和子目录

def dir():

from glob import glob

dir = []

dir = glob("path")

def all_sub_dir(dir):
{

     for item in dir:

            {
                b = "{}\*".format(item)
                dir += glob(b)
            }
         print(dir)
}

答案 5 :(得分:0)

要获取没有完整路径的简单文件夹列表,可以使用:

Directory.GetDirectories(parentDirectory).Select(d => Path.GetRelativePath(parentDirectory, d)