views:

1390

answers:

3

I've come across some strange behavior trying to get files that start with a certain string.

Please would someone give a working example on this:

I want to get all files in a directory that begin with a certain string, but also contain the xml extension.

for example:

 apples_01.xml
 apples_02.xml
 pears_03.xml

I want to be able to get the files that begin with apples.

So far I have this code

 DirectoryInfo taskDirectory = new DirectoryInfo(this.taskDirectoryPath);
 FileInfo[] taskFiles = taskDirectory.GetFiles("*.xml");

Thanks

+7  A: 
FileInfo[] taskFiles = taskDirectory.GetFiles("apples*.xml");
Cerebrus
haha, you gotta be kidding? Is this all?
JL
awesome, didnt know that
CodeSpeaker
Simplicity is the best answer. For more complex scenarios you may use a regular expression after retrieving all the files
Luis Filipe
GetFiles can be unreliable as it searches both the shortname and long name. I would second the recommendation to .GetFiles() and then filter using a regular expression. (Better yet, use the new .EnumerateFiles() in .net 4)
xkingpin
+1  A: 

var taskFiles = taskDirectory.GetFiles("*.xml").Where(p => p.Name.StartsWith("apples"));

CodeSpeaker
+1  A: 

GetFiles list files based on Search Pattern you applied.

Please refer to DirectoryInfo.GetFiles to know about how to use Search Pattern.

Ahmed
+1 for the MSDN link. I was about to post it but lost connection to the site.
Cerebrus