Filter for Multiple File Types
Using the GetFiles function, how can I go about filtering two (or more) file typ开发者_JAVA百科es?
The code I'm currently using is as follows:
folderlabel1.Text = folderBrowserDialog1.SelectedPath; //store
string extensions = "*.bsc>*.bs2";
string[] filterSplit = extensions.Split('>');
int filtercount = filterSplit.Length;
int count = 0;
listBox1.Items.Clear();
folder1 = new DirectoryInfo(Path.GetFullPath(@folderlabel1.Text));
for (count = 0; count < filtercount; count++)
{
fileEntries1 = folder1.GetFiles(filterSplit[count], SearchOption.AllDirectories);
}
foreach (FileInfo x in fileEntries1)
{
listBox1.Items.Add(x); //...add to folder display
}
So I'm trying to filter out both the *.bsc and *.bs2 file types...but obviously the way that it's being done here will just copy the second file type files over the first file types in the array. I'm wondering: 1. If there is a better way to do this 2. How do you add the contents of one array to the end of another? Is this possible? (because then using this method, I'll store the files in one array and then add them to another, instead of continuously overwriting the one array)
You can use the SelectMany
extension method against your filterSplit array to grab the files for each given extension.
var fileEntries1 = filterSplit.SelectMany(filter => folder1.GetFiles(filter, SearchOption.AllDirectories));
This will create an IEnumerable<FileInfo>
that you can then use to assign to your listbox.
For a non-LINQ approach, you could use a List<FileInfo>
and the AddRange
method inside of a foreach
against the array.
List<FileInfo> fileInfos = new List<FileInfo>();
foreach (string filter in filterSplit)
{
fileInfos.AddRange(folder1.GetFiles(filter, SearchOption.AllDirectories));
}
精彩评论