Reputation: 5293
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
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
Reputation: 1977
You can use OrderByDescending
DirectoryInfo dir = new DirectoryInfo (folderpath);
FileInfo[] files = dir.GetFiles().OrderByDescending(p => p.CreationTime).ToArray();
Upvotes: 42
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