简体   繁体   English

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

[英]how to list all sub directories in a directory

I'm working on a project and I need to list all sub directories in a directory for example how could I list all the sub directories in c:\我正在做一个项目,我需要列出目录中的所有子目录,例如如何列出 c:\ 中的所有子目录

Use Directory.GetDirectories to get the subdirectories of the directory specified by "your_directory_path" .使用Directory.GetDirectories获取"your_directory_path"指定目录的子目录。 The result is an array of strings.结果是一个字符串数组。

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

By default, that only returns subdirectories one level deep.默认情况下,它只返回一级深的子目录。 There are options to return all recursively and to filter the results, documented here , and shown in Clive's answer.有一些选项可以递归地返回所有内容并过滤结果, 记录在此处,并显示在克莱夫的回答中。


Avoiding an UnauthorizedAccessException避免 UnauthorizedAccessException

It's easily possible that you'll get an UnauthorizedAccessException if you hit a directory to which you don't have access.如果您访问了一个您无权访问的目录,很可能会遇到UnauthorizedAccessException

You may have to create your own method that handles the exception, like this:您可能必须创建自己的方法来处理异常,如下所示:

public class CustomSearcher
{ 
    public static List<string> GetDirectories(string path, string searchPattern = "*",
        SearchOption searchOption = SearchOption.AllDirectories)
    {
        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>();
        }
    }
}

And then call it like this:然后像这样调用它:

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

This traverses a directory and all its subdirectories recursively.这将递归遍历目录及其所有子目录。 If it hits a subdirectory that it cannot access, something that would've thrown an UnauthorizedAccessException , it catches the exception and just returns an empty list for that inaccessible directory.如果它遇到一个它无法访问的子目录,它会抛出UnauthorizedAccessException ,它会捕获异常并只为该无法访问的目录返回一个空列表。 Then it continues on to the next subdirectory.然后它继续到下一个子目录。

像这样简单:

string[] folders = System.IO.Directory.GetDirectories(@"C:\My Sample Path\","*", System.IO.SearchOption.AllDirectories);
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);

        }
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();
        }
    }
}

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

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

Here's Best and Fastest Way To List All Directories and Subdirectories by Skipping System.UnauthorizedAccessException这是通过跳过 System.UnauthorizedAccessException 列出所有目录和子目录的最佳和最快方法

A simple recursive method with action to retrieve at realtime, preparing a list and returning to parent takes a lot of time, this call back function helps a lot to retrieve at realtime instead of preparing and returning back一个简单的具有实时检索动作的递归方法,准备一个列表并返回父项需要很多时间,这个回调 function 有助于实时检索而不是准备和返回

using System.IO;

private static void ListDirectories(string Path, Action<string> Listen){
    try
    {
        foreach(string Node in Directory.GetDirectories(Path)){
            Listen(Node);
            ListDirectories(Node, Listen);
        }
    } catch {}
}

Usase用濑

static void Main(string[] args)
{
    ListDirectories(@"C:\", (dir) =>
    {
        Console.WriteLine(dir);
    });
}

show all directry and sub directories显示所有目录和子目录

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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用uribuilder获取目录下的所有子目录 - How to get all sub directories under a directory using uribuilder 使用List &lt;&gt;中的映射和索引收集目录和子目录 - Collect Directory and Sub Directories with mapping and index in a List<> 有没有比这更快的方法来查找目录和所有子目录中的所有文件? - Is there a faster way than this to find all the files in a directory and all sub directories? 创建目录+子目录 - Create Directory + Sub Directories C#-如何在具有创建日期的目录中生成文件名和子目录的列表 - C# - How to generate a list of file names and sub directories in a directory with creation date 列出一个目录+子目录中的所有文件和目录 - List all files and directories in a directory + subdirectories 如何使用treeView列出子目录中的文件而不显示根目录? - How to use treeView to list the Files within sub Directories without showing the root directory? 如何在不使用递归的情况下列出目录中的所有文件夹和子文件夹 - How to list all the folders and sub folders in a directory without using recursion 如何获取目录和子目录的列表C#WPF - How to get a list of directories and sub directories C# WPF 无法使用c#列出Linux中的所有子目录 - Cannot list all the sub-directories in Linux using c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM