将三个子目录中的文件添加到C#中自己的列表中

时间:2018-06-22 14:47:17

标签: c# file

我想知道是否有任何方法可以将三个子目录中的文件名放入自己的列表中。文件路径为Main->folder->subfolder,共有三个文件夹,每个文件夹都有一个子文件夹,我需要从中获得文件名。有什么办法吗?我目前已编写此代码,以将所有文件名的主列表放入主列表

public static List<String> DirectorySearch(string dir)
{
    List<String> ListFiles = new List<String>();
    try
    {
        foreach (string f in Directory.GetFiles(dir))
        {
            var GetFileName = Path.GetFileName(f);
            //Console.WriteLine(GetFileName);
            ListFiles.Add((GetFileName).ToString());
        }

        foreach (string d in Directory.GetDirectories(dir))
        {
            var GetDirName = Path.GetFileName(d);

            ListFiles.AddRange(DirectorySearch(d));
            ListFiles.Add((GetDirName).ToString());
        }                 
        return ListFiles;
    }

如果代码太多,编写太多,请告诉我,并可能指向正确的方向,以便我自己解决其余问题。任何建议都是有帮助的!

2 个答案:

答案 0 :(得分:0)

是的,这是可能的。内嵌评论

/// By convention, it's better to use the primitive type string as opposed to the 
/// wrapping Type String except when making calls to the String static methods
public static Dictionary<string, List<string>> DirectorySearch(string dir)
    {
        /// I would define a dictionary<string, List<string>> to house the file names
        /// and folder names

        var fileDictionary = new Dictionary<string, List<string>>();

        /// note: variables should be camel case to avoid confusion between them and
        /// classes or properties (which are Pascal Cased)
        try
        {
            var listFiles = new List<string>();
            foreach (string fileName in Directory.GetFiles(dir))
            {
                listFiles.Add(Path.GetFileName(fileName));
            }
            /// First, we add all the parent directory's files to the dictionary
            fileDictionary.Add(dir, listFiles);

            /// Then we iterate over the subdirectory and add those files to their
            /// own key in the fileDictionary
            foreach (string subDirectory in Directory.GetDirectories(dir))
            {
                listFiles = new List<string>();
                foreach (string fileName in Directory.GetFiles(subDirectory))
                {
                    listFiles.Add(Path.GetFileName(fileName));
                }
                fileDictionary.Add(subDirectory, listFiles);
            }
        }
        catch(Exception ex)
        {
            /// Do something with your exception
        }
        return fileDictionary;
    }

答案 1 :(得分:0)

我想您可以使用LINQ使用以下简洁代码:

 List<string> ListFiles = Directory.GetDirectories(dir)
    .SelectMany(d => Directory.GetDirectories(d).SelectMany(Directory.EnumerateFiles))
    .ToList();

这将返回子文件夹中的所有文件路径。