i am trying to get a list of file开发者_StackOverflows 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?
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 ..
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
}
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;
}
}
精彩评论