DirectoryInfo.getFiles beginning with
Asked Answered
H

2

27

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");
Helladic answered 29/7, 2009 at 8:14 Comment(0)
I
56
FileInfo[] taskFiles = taskDirectory.GetFiles("apples*.xml");
Iphigeniah answered 29/7, 2009 at 8:16 Comment(2)
Simplicity is the best answer. For more complex scenarios you may use a regular expression after retrieving all the filesWindowpane
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)Aloysia
S
6
var taskFiles = taskDirectory.GetFiles("*.xml").Where(p => p.Name.StartsWith("apples"));
Sitka answered 29/7, 2009 at 8:17 Comment(1)
var _FileInfoArray = _DirectoryInfo.GetFiles("*.txt").Where(x => x.Name.Contains(_FileName));Tray

© 2022 - 2024 — McMap. All rights reserved.