Getting FileInfo[]

J

John Bowman

Hi All,

..NET 1.1... I'm wondering if there is any approach more convenient to get a
list of FileInfo objects than the following. For example, if I wanted to get
1 list of all the Exe's and all the Dll's and all the Txt's in a folder, if
appears I need to do something like the following:

ArrayList InterestingFiles = new ArrayList();
DirectoryInfo di = new DirectoryInfo(@"C:\My Folder");

FileInfo[] EXEs = di.GetFiles("*.exe");
FileInfo[] DLLs = di.GetFiles("*.dll");
FileInfo[] TXTs = di.GetFiles("*.txt");

InterestingFiles.AddRange(EXEs);
InterestingFiles.AddRange(DLLs);
InterestingFiles.AddRange(TXTs);

foreach(FileInfo fi in InterestingFiles)
{
MessageBox.Show(fi.Name);
}

It would be really cool if the GetFiles method accepted an array of
searchPatterns to accomplish this in 1 line instead of 6... but alas I can
not find anything like the following.
eg,

string[] exts = {"*.exe", "*.dll", "*.txt"}
FileInfo[] AllInterestingFiles = di.GetFiles(exts);

This would be especially more convenient when the list of file extensions we
cared about was rather long. I suppose I could write a simple
FileInfoCollection class whose constructor accepted the array of exts and a
path, but that sort of seems like overkill. Anyone have any better ideas?

I realize that I probably should use a collection of FileInfo objects
instead of an array list for the real thing, but for this example purpose
I'm being lazy <g>.

TIA,
 
N

Nicholas Paldino [.NET/C# MVP]

John,

This would seem to be the best way. If you encapsulated it into a
function that has a params argument, you could actually do this:

public static FileInfo[] FindFiles(DirectoryInfo directory, params string[]
extensions)
{
// The values to return.
ArrayList retVal = new ArrayList();

// Cycle through the extensions, and add to a return value.
foreach (string extension in extensions)
{
// Find the files, and add to the return value.
retVal.AddRange(directory.GetFiles(extension));
}

// Return the array.
return (FileInfo[]) retVal.ToArray(typeof(FileInfo));
}

Then, you could just do:

foreach(FileInfo fi in FindFiles(new DirectoryInfo(@"C:\My Folder"),
"*.exe", "*.dll", "*.txt"))
{
MessageBox.Show(fi.Name);
}

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top