I'm trying to get a list of all files in a selected folder using UWP and C#. I need to select a folder and display all audio files in that folder (including subfolders of the root folder
I have the following code:
var folderPicker = new FolderPicker();
folderPicker.SuggestedStartLocation = PickerLocationId.Desktop;
folderPicker.FileTypeFilter.Add("*");
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
List<string> fileTypeFilter = new List<string>();
fileTypeFilter.Add(".mp3");
fileTypeFilter.Add(".mp3");
fileTypeFilter.Add(".wma");
fileTypeFilter.Add(".wav");
fileTypeFilter.Add(".ogg");
fileTypeFilter.Add(".flac");
fileTypeFilter.Add(".aiff");
fileTypeFilter.Add(".aac");
QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderByDate, fileTypeFilter);
StorageFileQueryResult results = folder.CreateFileQueryWithOptions(queryOptions);
IReadOnlyList<StorageFile> sortedFiles = await results.GetFilesAsync();
foreach (StorageFile item in sortedFiles)
{
AudioFilesLV.Items.Add(item.Path.ToString());
}
However once I select the folder I get the following error:
System.ArgumentException: 'Value does not fall within the expected range.'
The folder I am selecting contains around 100 MP3 files
Does anyone have any idea what I am doing wrong?
Thanks in advance
Seems to be a known issue with the CommonFileQuery.OrderByDate. Apparently you can only use CommonFileQuery.OrderByDate with the folders in the KnownFolders enumeration. If I change your code to use CommonFileQuery.DefaultQuery it works.
You could just use an OrderBy as follows if they aren't coming back in date order:
foreach (StorageFile item in sortedFiles.OrderBy(a => a.DateCreated))