如何列出目录中的所有子目录 [英] how to list all sub directories in a directory

查看:196
本文介绍了如何列出目录中的所有子目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个项目,我需要列出所有子目录中例如目录我怎么能列出所有的子目录在C:\

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:\

推荐答案

使用 Directory.GetDirectories 获得通过的your_directory_path<指定的目录的子目录/ em>的。其结果是一个字符串数组

Use Directory.GetDirectories to get the subdirectories of the directory specified by "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.

避免了UnauthorizedAccessException

这无疑可能你会得到一个 UnauthorizedAccessException 如果你打一个目录,您没有访问。

It's easily possible that you'll get an UnauthorizedAccessException if you hit a directory to which you don't have access.

您可能必须创建你自己的方法处理异常,就像这样:

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



然后调用它这样

And then call it like this:

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

这篇关于如何列出目录中的所有子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆