Reputation: 320
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
}
Upvotes: 0
Views: 2209
Reputation: 2754
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
}
Upvotes: 1
Reputation: 4974
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.
Upvotes: 1
Reputation: 181
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.
Upvotes: 1