JOE SKEET
JOE SKEET

Reputation: 8098

get files from multiple directories

i am trying to get a list of files into an array or list from multiple directories

currently i am doing:

tempbatchaddresses = Directory.GetFiles(@"c:\", "*.log");

but i also need tempbatchaddresses += Directory.GetFiles(@"d:\", "*.log");

and a third one as well. i need to add the file locations of files from 3 different directories.

how do i do this?

Upvotes: 1

Views: 8460

Answers (3)

Mahesh Velaga
Mahesh Velaga

Reputation: 21991

tempBatchAddresses = Directory.GetFiles(@"c:\", "*.log").ToList();

tempBatchAddresses.AddRange(Directory.GetFiles(@"d:\", "*.log").ToList());

tempBatchAddresses.AddRange(Directory.GetFiles("some dir", "some pattern").ToList());

and so on ..

Upvotes: 7

Anthony Pegram
Anthony Pegram

Reputation: 126794

There are a myriad number of similar ways to tackle the problem. Here's one.

static void Main()
{
    IEnumerable<string> files = GetFiles("*.log", @"C:\", @"D:\", @"E:\");
}

static IEnumerable<string> GetFiles(string searchPattern, params string[] directories)
{
    foreach (string directory in directories)
    {
        foreach (string file in Directory.GetFiles(directory, searchPattern))
            yield return file;
    }
}

Upvotes: 1

slugster
slugster

Reputation: 49974

Try something like this:

List<string> myFiles = new List<string>();
myFiles.AddRange(Directory.GetFiles(@"c:\", "*.log"));
...etc...

foreach (string file in myFiles)
{
    //do whatever you want
}

Upvotes: 4

Related Questions