Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I create Windows form for read dynamic file with folder browsing dialog. I need filter multiple extension. For example, ".txt", ".pdf".. here, I tried using different methods. But I didn't catch correct way. there is select if both extensions. I need to if file contain ".pdf" or ".txt" or both.

What I have tried:

if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
                    {
                        string[] files = Directory.GetFiles(fbd.SelectedPath);
                        textBox1.Text = fbd.SelectedPath.ToString();
                        //var result = new List<string>();
                        string path = "fbd.SelectedPath";

                        List<string> result = new List<string>();
                        string[] extensions = { ".txt", ".JNL" };

                        foreach (string file in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories)
                            .Where(s => extensions.Any(ext => ext == Path.GetExtension(s))))
                        {
                            result.Add(file);
                            Console.WriteLine(file);
                        }
                        

                    }
Posted
Updated 14-Apr-22 0:47am

1 solution

The Directory.EnumerateFiles method can only accept one type of mask, which is what you're doing currently. You can use LINQ to compile an aggregate collection of records:

C#
// The extensions you're after, note the asterisk
string[] extensions = { "*.txt", "*.jnl" };

// Create a reference to the selected directory
DirectoryInfo directory = new DirectoryInfo(fbd.SelectedPath);

// Here we essentially loop through the extensions above and for
// each extension we call EnumerateFiles(), the resulting files
// get aggregated together into one enumerable
IEnumerable<string> files = extensions.SelectMany(
  e => directory.EnumerateFiles(e, SearchOption.AllDirectories)
);

// Now you can do what you like with the files!
foreach (string file in files)
{
  Console.WriteLine(file);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900