How to get files from exact subdirectories

南楼画角 提交于 2019-12-23 11:56:58

问题


I've managed to get files out of "root" folder subdirectories, but I also get files from these subdirectories directories2, which I don't want to.

Example: RootDirectory>Subdirectories (wanted files)>directories2 (unwanted files)

I've used this code:

public void ReadDirectoryContent() 
{
  var s1 = Directory.GetFiles(RootDirectory, "*", SearchOption.AllDirectories);
  {
  for (int i = 0; i <= s1.Length - 1; i++)
  FileInfo f = new FileInfo(s1[i]); 
  . . . etc
  }
}

回答1:


Try this :

var filesInDirectSubDirs = Directory.GetDirectories(RootDirectory)
    .SelectMany(d=>Directory.GetFiles(d));

foreach(var file in filesInDirectSubDirs)
{
    // Do something with the file
    var fi = new FileInfo(file);
    ProcessFile(fi);
}

The idea is to first select 1st level of subdirectories, then "aggregate" all files using Enumerable.SelectMany method




回答2:


You have to change SearchOption.AllDirectories to SearchOption.TopDirectoryOnly, because the first one means that it gets the files from the current directory and all the subdirectories.

EDIT:

The op wants to search in direct child subdirectories, not the root directory.

public void ReadDirectoryContent() 
{
    var subdirectories = Directory.GetDirectories(RootDirectory);
    List<string> files = new List<string>();

    for(int i = 0; i < subdirectories.Length; i++)
       files.Concat(Directory.GetFiles(subdirectories[i], "*", SearchOption.TopDirectoryOnly));
}


来源:https://stackoverflow.com/questions/13953724/how-to-get-files-from-exact-subdirectories

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!