0

So i'm using the simple

ImgFilesCount = ImgDirInfo.GetFiles("*.jpg").Length;

to figure out how many files are in a dir. But I need it to only count files that have exactly 26 characters in the file name. I tried

ImgFilesCount = ImgDirInfo.GetFiles("?????????????????????????.jpg").Length;

But it didn't work. Is the only option to do a foreach loop and check each filename and increment the counter? I have a feeling linq can probably do this with a .Where statement but I don't know any Linq.

Matt Winer
  • 495
  • 9
  • 26

3 Answers3

5

Maybe

int count = ImgDirInfo.EnumerateFiles("*.jpg").Count(f => f.Name.Length == 26);

EnumerateFiles is more efficient since it doesn't need to load all files into memory before it starts processing.

  • When you use EnumerateFiles, you can start enumerating the collection of FileInfo objects before the whole collection is returned.
  • When you use GetFiles, you must wait for the whole array of FileInfo objects to be returned before you can access the array.
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 1
    Good point about `EnumerateFiles`. Just tiny note: isn't `Count` will load all files making streaming nature of `EnumerateFiles` irrelevant? – Ilya Ivanov May 17 '13 at 23:59
  • @IlyaIvanov Well, no. That's the whole beauty of iterators. The `Count` extension method consumes the query during the counting process. – SimpleVar May 18 '13 at 00:00
  • @YoryeNathan as result making more calls to hard disk? – Ilya Ivanov May 18 '13 at 00:02
  • @YoryeNathan: In this case Ilya is right since `Count` needs to enumerate all files with the given search pattern. So in general it's better to use `Directory.EnumerateFiles` instead if you only need the filename. – Tim Schmelter May 18 '13 at 00:03
  • @IlyaIvanov It's Performance vs Memory. I usually go for performance, but it depends on the situation. This is only to point out that in some cases the `EnumerateFiles` method is more appropriate *even though* it does consume the query in the end. – SimpleVar May 18 '13 at 00:03
  • @YoryeNathan agree, but it's hard to say where performance is better without empirical evidence. Anyway, I should definitely need to remember `EnumerateFiles`. I've knew about `ReadLines` vs `ReadAllLines`, now Tim brought another streaming vs non-streaming files reading, – Ilya Ivanov May 18 '13 at 00:05
3
ImgFilesCount = ImgDirInfo.GetFiles("*.jpg")
                          .Where(file => file.Name.Length == 26)
                          .Count();
Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90
0

Something like this?

        string[] files = Directory
                         .EnumerateFiles(@"c:\Users\x074\Downloads" , "*.jpg" , SearchOption.AllDirectories )
                         .Where( path => Path.GetFileName(path).Length > 20 )
                         .ToArray()
                         ;
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135