简体   繁体   中英

Get List of StorageFile ordered by last modified date

I'm trying to accomplish what should be a very easy task which is to obtain a list of StorageFile from a StorageFolder in descending order of date modified.

Current code that retrieves a list but not ordered

                Task<IReadOnlyList<StorageFile>> task = folder.Result.GetFilesAsync().AsTask();
                task.Wait();
                return task.Result.Select(z => z.Name).ToArray();

StorageFile has a property for DateCreated but nothing similar for DateModified.

I looked into using GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByDate) but this is only for files in a Windows library.

In WinRT, you need to call StorageFile.GetBasicPropertiesAsync . The BasicProperties object you'll get back has a dateModified property that you can use for your sort. You can find code snippets in scenario 6 of the File access sample .

You can also achieve your goals using a custom file query rather than one of the common queries. For this I recommend looking at the Programmatic file search sample , and I discuss these in Chapter 11 of my free ebook, Programming Windows Store Apps with HTML, CSS, and JavaScript, 2nd Edition (don't let the JS focus fool you--all the WinRT discussions are completely applicable to all languages).

If your case, you can create a simple custom query by initializing a common one, then changing the sort order. Here's a modification I made to scenario 1 of the aforementioned sample for this purpose, replacing line 42:

// initialize queryOptions using a common query
QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypeFilter);

// clear all existing sorts
queryOptions.SortOrder.Clear();

// add descending sort by date modified
SortEntry se = new SortEntry();
se.PropertyName = "System.DateModified";
se.AscendingOrder = false;            
queryOptions.SortOrder.Add(se);

In your code, just call folder.CreateFileQueryWithOptions(queryOptions) followed by queryResult.GetFilesAsync, and the results list should be exactly what you want.

StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(queryOptions);
IReadOnlyList<StorageFile> files = await queryResult.GetFilesAsync();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM