分享

C语言‖遍历指定目录

 我爱青花瓷 2023-09-15

下面提供了三个函数,这些函数可以帮助你遍历指定目录的所有子目录和文件。


csharp

using System.IO;

using System.Collections.Generic;


public class DirectoryTraversal

{

    // 递归遍历目录,返回所有子目录和文件的路径

    public List<string> RecursiveDirectoryTraversal(string path)

    {

        List<string> result = new List<string>();

        RecursiveDirectoryTraversalInternal(path, "", result);

        return result;

    }


    // 递归遍历目录的核心方法,用于实现递归遍历并添加路径到结果列表

    private void RecursiveDirectoryTraversalInternal(string path, string subPath, List<string> result)

    {

        DirectoryInfo info = new DirectoryInfo(path);


        if (info.Exists)

        {

            foreach (DirectoryInfo subDir in info.GetDirectories())

            {

                RecursiveDirectoryTraversalInternal(subDir.FullName, subPath + subDir.Name + "/", result);

            }


            foreach (FileInfo file in info.GetFiles())

            {

                result.Add(subPath + file.Name);

            }

        }

    }


    // 获取指定目录下所有子目录的名称,不包括文件

    public List<string> GetSubDirectoryNames(string path)

    {

        List<string> result = new List<string>();

        RecursiveDirectoryTraversalInternal(path, "", result);

        return result;

    }

}


这个类中的方法可以用于遍历指定目录的所有子目录和文件。RecursiveDirectoryTraversal方法会返回所有子目录和文件的完整路径列表,而GetSubDirectoryNames方法则只会返回子目录的名称列表。请注意,在实际使用中,你需要确保有足够的权限访问指定的目录。

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多