17

I want to get a list of files in a folder sorted by their creation date using C#.

I am using the following code:

        if(Directory.Exists(folderpath))
        {
            DirectoryInfo dir=new DirectoryInfo (folderpath);
            FileInfo[] files = dir.GetFiles().OrderBy(p=>p.CreationTime).ToArray();
            foreach (FileInfo file in files)
            {
              ......
            }
        }

This will give the ascending order of the creation time. I actually want get the most recently created file in the first position of my array (descending order).

ouflak
  • 2,458
  • 10
  • 44
  • 49
neel
  • 5,123
  • 12
  • 47
  • 67

3 Answers3

40

You can use OrderByDescending

DirectoryInfo dir = new DirectoryInfo (folderpath);

FileInfo[] files = dir.GetFiles().OrderByDescending(p => p.CreationTime).ToArray();
Rikin Patel
  • 8,848
  • 7
  • 70
  • 78
damienc88
  • 1,957
  • 19
  • 34
4

DirectoryInfo:Exposes instance methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited.

Use this:

var di = new DirectoryInfo(directory);
var filesOrdered = di.EnumerateDirectories()
                    .OrderByDescending(d => d.CreationTime)
                    .Select(d => d.Name)
                    .ToList();
Community
  • 1
  • 1
1

Here is the Java version, just as a pointer for ideas:

protected File[] getAllFoldersByDescendingDate(File folder)
{
    File[] allFiles = folder.listFiles(new FilenameFilter()
    {
        @Override
        public boolean accept(File current, String name)
        {
            return new File(current, name).isDirectory();
        }
    });
    Arrays.sort(allFiles, new Comparator<File>()
    {
        public int compare(final File o1, final File o2)
        {
            return Long.compare(o2.lastModified(), o1.lastModified());
        }
    });
    if ( allFiles == null)
    {
        allFiles = new File[]{};
    }
    return allFiles;
}
djangofan
  • 28,471
  • 61
  • 196
  • 289