views:

392

answers:

2

Given a list of FileInfo objects, how do I sort them by date? Specifically I want to sort them by CreationTime in descending order.

+1  A: 

DirectoryInfo.GetFiles() returns an array of FileInfo objects. I created a generic list to hold the FileInfo objs, and sorted using a custom comparer.

logDir = r"C:\temp"
fileInfosArray = DirectoryInfo(logDir).GetFiles("*.log")
fileInfosList = List[FileInfo]()
fileInfosList.AddRange(fileInfosArray)
fileInfosList.Sort(FileInfoCompareCreationTimeDesc)
for fileInfo in fileInfosList:
    print fileInfo.CreationTime, fileInfo.LastAccessTime, fileInfo.LastWriteTime, fileInfo.Name

# comparison delegate for FileInfo objects: sort by CreationTime Descending
def FileInfoCompareCreationTimeDesc(fileInfo1, fileInfo2):
    return fileInfo2.CreationTime.CompareTo(fileInfo1.CreationTime)
Tom E
+2  A: 

The Pythonic way of doing this would be:

fileInfos = list(DirectoryInfo(path).GetFiles())
fileInfos.sort(key=lambda f: f.CreationTime, reverse=True)

The list sort method takes a key function that is used to get the sort key for each item.

wilberforce