Click here to Skip to main content
15,886,664 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Through this site I have figured out my recent problem when trying to scan for file extensions such as "*.txt", but I cannot figure out how to scan for multiple file types such as ".txt" and ".exe" at the same time?

The code that works for a single file extension at a time is:
VB
dim FExtension as string = "*.txt"
 For Each file1 In IO.Directory.GetFiles(dir, FExtension)


How can I add?
C#
dim FExtension as string = "*.txt" and '*.exe" and "*.sys" 

and so forth?

Thank you in advance for your help! :)
Posted
Updated 1-Jul-16 6:29am
v2

You can't.

GetFiles method only accepts one option in the overload.

Either run it twice with a different extension, or, run it without the filter and afterward filter the result in a loop.
 
Share this answer
 
You could use LinQ to retrieve all files with multiple extensions like this:-

C#
var files = Directory.GetFiles(@"C:\yourPath", "*.*", SearchOption.AllDirectories).
                Where(s => s.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) || s.EndsWith(".doc", StringComparison.OrdinalIgnoreCase));


Just be aware that the original query will return all files in yourPath, so if you pass in say C:\ you will start getting performance issues.
 
Share this answer
 
I would try to recurse thru the file extensions something like this.
Be Warned though it will take some time to return all of the information even for just 1 file extension if you choose a root start location.
VB
Dim FExtension1 As String = "*.txt"
Dim FExtension2 As String = "*.exe"
Dim FExtension3 As String = "*.sys"

For Each file1 In IO.Directory.GetFiles(Dir, FExtension1)
    ' add to list box or append to text box or a Datagridview
Next

For Each file1 In IO.Directory.GetFiles(Dir, FExtension2)
    ' add to list box or append to text box or a Datagridview
Next

For Each file1 In IO.Directory.GetFiles(Dir, FExtension3)
    ' add to list box or append to text box or a Datagridview
Next
 
Share this answer
 
v3
Comments
Dale 2012 14-Nov-11 21:28pm    
THANK YOU SOOOOOOOO MUCH IT WORKS!!!!! yeah!!!
C#
Dim supportedExtensions As String = "*.zip,*.aaa,*.bbb,*.ccc,*.ddd"
Dim files As String() = Directory.GetFiles(romPath, "*.*", SearchOption.AllDirectories)
Array.Sort(files)

For Each fi As String In files
 If supportedExtensions.Contains(Path.GetExtension(fi)) Then
 ...
 End If
Next
 
Share this answer
 
Comments
Richard MacCutchan 1-Jul-16 13:28pm    
Please do not post in old questions; this one is nearly 5 years old.

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