所有文件夹和文件x深一览文件夹、文件、深一览

2023-09-06 21:57:39 作者:心痛的瞬间

我希望拥有的所有文件夹和文件x深的名单。

I want to have list of all folders and files for x depth.

如果x为2比我将所有文件夹和文件,从第一个文件夹,并从第一个文件夹的文件夹所有文件夹和文件的信息。

If x is 2 than I will have information about all folders and files from first folder, and all folders and files from folders in first folder.

如何做到这一点?

推荐答案

这code会做什么其他的答案都在做,而且还返回该文件夹的名称(因为这似乎是你问的一部分)。这将需要的.Net 4.0。其中,如果你想跟踪的文件夹中,哪些文件可以返回一个包含文件列表及文件夹列表的元组。

This code will do what other answers are doing, but also return the folder names (as that appears to be part of what you are asking). This will require .Net 4.0. If you wish to keep track of which are folders and which are files you could return a tuple containing a list of files and a list of folders.

List<string> GetFilesAndFolders(string root, int depth)
{
    var list = new List<string>();
    foreach(var directory in Directory.EnumerateDirectories(root))
    {
        list.Add(directory);
        if (depth > 0)
        {
            list.AddRange(GetFilesAndFolders(directory, depth-1));
        }
    }

    list.AddRange(Directory.EnumerateFiles(root));

    return list;
}

编辑:code,保持文件夹和文件分开

Code that keeps the folders and files separate

Tuple<List<string>,List<string>> GetFilesAndFolders(string root, int depth)
{
    var folders = new List<string>();
    var files = new List<string>();
    foreach(var directory in Directory.EnumerateDirectories(root))
    {
        folders.Add(directory);
        if (depth > 0)
        {
                var result = GetFilesAndFolders(directory, depth-1);
                folders.AddRange(result.Item1);
                files.AddRange(result.Item2);
        }
    }

    files.AddRange(Directory.EnumerateFiles(root));

    return new Tuple<List<string>,List<string>>(folders, files);
}