neel
neel

Reputation: 5293

Get a list of files in a directory in descending order by creation date using C#

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).

Upvotes: 19

Views: 53522

Answers (3)

djangofan
djangofan

Reputation: 29669

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;
}

Upvotes: 1

damienc88
damienc88

Reputation: 1977

You can use OrderByDescending

DirectoryInfo dir = new DirectoryInfo (folderpath);

FileInfo[] files = dir.GetFiles().OrderByDescending(p => p.CreationTime).ToArray();

Upvotes: 42

user1968030
user1968030

Reputation:

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();

Upvotes: 5

Related Questions