How to read File names recursively from subfolder using LINQ

前端 未结 5 1177
鱼传尺愫
鱼传尺愫 2021-01-13 09:36

How to read file name with dll extension from a directory and from its subfolders recursively using LINQ or LAMBDA expression.

Now i\'m using Nested for

5条回答
  •  有刺的猬
    2021-01-13 10:23

    If you really want to do it with a recursive lambda expression here you go:

    Action> discoverFiles = null;
    
    discoverFiles = new Action>((dir, list) =>
        {
            try
            {
                foreach (var subDir in Directory.GetDirectories(dir))
                    discoverFiles(string.Concat(subDir), list);
    
                foreach (var dllFile in Directory.GetFiles(dir, "*.dll"))
                {
                    var fileNameOnly = Path.GetFileName(dllFile);
                    if (!list.Contains(fileNameOnly))
                        list.Add(fileNameOnly);
                }
            }
            catch (IOException)
            {
                // decide what to do here
            }
        });
    
    // usage:
    var targetList = new List();
    discoverFiles("c:\\MyDirectory", targetList);
    
    foreach (var item in targetList)
        Debug.WriteLine(item);
    

    Note: this is probably several times slower (and way harder to read/debug/maintain) than the previous answers, but it does not stop if there is an I/O exception somewhere.

提交回复
热议问题