Using c# GetFiles Length but only count the files with certain amount of chars in filename

StackOverflow https://stackoverflow.com/questions/16619346

  •  29-05-2022
  •  | 
  •  

質問

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.

役に立ちましたか?

解決

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.

他のヒント

ImgFilesCount = ImgDirInfo.GetFiles("*.jpg")
                          .Where(file => file.Name.Length == 26)
                          .Count();

Something like this?

        string[] files = Directory
                         .EnumerateFiles(@"c:\Users\x074\Downloads" , "*.jpg" , SearchOption.AllDirectories )
                         .Where( path => Path.GetFileName(path).Length > 20 )
                         .ToArray()
                         ;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top