Search code examples
c#.netfileinfo

DirectoryInfo GetFiles TOP number


I want to return 10 files only from a directory. Is this possible?

DirectoryInfo d = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/xml"));

FileInfo[] files = d.GetFiles("*.xml");

This way returns all XML files, but I want to get just the first ten.


Solution

  • You can add the extension method Take(10) to only grab the first 10 files.

    var d = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/xml"));
    var files = d.GetFiles("*.xml").OrderByDescending(fi=>fi.LastWriteTime).Take(10);