简体   繁体   中英

DirectoryInfo.GetFiles() from specific multiple folders

Is there a simple way to get file info from specific multiple folders rather than All Directories. I have the following file structure:

~/docs/folder1/
~/docs/folder2/
~/docs/folder3/

I only want to list the files in folder1 and folder3. I'm currently using the following which returns all files in ~/docs/.

DirectoryInfo info = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/docs/"));
foreach (var fi in info.GetFiles("*", SearchOption.AllDirectories))
{
//do stuff with files                  
}

Shamelessly copied your original code, and added a few suggestions. Basically, if you know what folders you want to process (or even if it is determined by user input) store them in a list and iterate over that.

List<String> folders = new List<String> { "Folder1", "Folder3" };
foreach(var folder in folders)
{
    String rootDir = "~/docs/";
    StringBuilder sb = new StringBuilder();
    String find = sb.AppendFormat("{0}{1}/", rootDir, folder).ToString();
    DirectoryInfo info = new DirectoryInfo(HttpContext.Current.Server.MapPath(find));
    foreach (var fi in info.GetFiles("*", SearchOption.AllDirectories))
    {
        //do stuff with files
    }
}

As an extra step, you could even do this in a parallel foreach too.

You could use LINQ to filter the results:

var folderNames = new[] { "folder1", "folder2" };
foreach (var fi in info.GetFiles("*", SearchOption.AllDirectories)
                       .Where(x => folderNames.Contains(x.Directory.Name)))

or you could use LINQ to get the results in the first place:

var folderPaths = new[] {"~/docs/folder1/", "~/docs/folder3/"};
foreach (var fi in folderpaths
                     .SelectMany(x => 
                      new DirectoryInfo(HttpContext.Current.Server.MapPath(x))
                            .GetFiles("*", SearchOption.AllDirectories)))

Disclaimer: these do not produce the same results. If you can be more specific about the files you want (including/excluding subdirs, etc) I can be more specific about the queries.

Although other answer also work but I would do like this in one go..

 var directories = Directory.GetDirectories("~/docs/", "*.*", SearchOption.AllDirectories);
 foreach (var files in from directory in dirs where directory.Contains("Folder2") == false select Directory.GetFiles(directory))
 {
    List<String> filesList = files.ToList();
  // Do Something with your files
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM