8

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.

Ani
  • 111,048
  • 26
  • 262
  • 307
Beginner
  • 83
  • 1
  • 3

4 Answers4

13

If you're using .NET4 then you should probably use EnumerateFiles instead, along with the Take extension method:

var d = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/xml"));
FileInfo[] files = d.EnumerateFiles("*.xml").Take(10).ToArray();
LukeH
  • 263,068
  • 57
  • 365
  • 409
  • 2
    This is the correct solution. The solution by Jake Pearson currently marked as correct uses GetFiles which returns an array type which means ALL the files will be materialised before you can apply the LINQ statement Take. Using EnumerateFiles returns an IEnumerable which will only walk the amount of files applied by the Take... LINQ can be so dangerous if you don't watch the return types and note how they behave :) – Paul Carroll Sep 19 '12 at 05:31
12

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);
Jake Pearson
  • 27,069
  • 12
  • 75
  • 95
  • very nice. I will put correct. How can I order by changed date? – Beginner May 05 '11 at 14:48
  • @Jake Small mistake: Take returns an `IEnumerable` and you assign it to a `FileInfo[]` – CodesInChaos May 05 '11 at 15:00
  • @Beginner you can do d.GetFiles().Take(3).OrderBy( r => r.CreationTime).ToArray(); for orderBy – anishMarokey May 05 '11 at 15:01
  • @Beginner Put `.OrderBy(fi=>fi.LastWriteTime)` or `.OrderByDescending(fi=>fi.LastWriteTime)` before the `.Take(10)`. Assuming you want the 10 most recently changed files and not 10 random files you need to sort first and then limit the number with take. So not what @anish recommended – CodesInChaos May 05 '11 at 15:02
  • SHOWWWWWWWWWWWWWWW .OrderByDescending(fi=>fi.LastWriteTime) – Beginner May 05 '11 at 15:05
1

you have to the same what Jake mentioned, but not FileInfo[] files

      DirectoryInfo d = new DirectoryInfo("~/xml");
      IEnumerable< FileInfo> files = d.GetFiles().Take(10);

                         OR

     DirectoryInfo d = new DirectoryInfo("~/xml");
      FileInfo[] files = d.GetFiles().Take(10).ToArray();
anishMarokey
  • 11,279
  • 2
  • 34
  • 47
-1
  var directory = new DirectoryInfo(Tab16_mainPath);


  var myFile = (from f in directory.GetFiles().Take(3)
                orderby f.LastWriteTime descending
                select f).ToArray();
Craig
  • 1
  • 1