Search code examples
c#fileinfo

Get first x items from FileInfo


I have a FileInfo in C# that looks like this:

        DirectoryInfo dir = new DirectoryInfo(folder);
        FileInfo[] files = dir.GetFiles("Car*", SearchOption.TopDirectoryOnly);

I want to be able to select the first x items, let's say 30, of the files in files and remove the rest from files. How do I do that without just looping through it from 0 to 29?


Solution

  • Instead of using GetFiles, use EnumerateFiles plus Take and ToArray:

    DirectoryInfo dir = new DirectoryInfo(folder);
    FileInfo[] files = dir.EnumerateFiles("Car*", SearchOption.TopDirectoryOnly).Take(30).ToArray();
    

    This will create an array with up to the first thirty items found in the directory. This has the benefit that on really large directories it only returns thirty items at most. GetFiles will return every file in the directory first which can take time if there's a lot of files. EnumerateFiles on the otherhand, returns an IEnumerable<FileInfo> which allows you to "stream" the results and apply LINQ operators before collecting them into an array or List.

    Note: you will need to make sure that you have the appropriate using directive at the top of your file:

    using System.Linq;