Ra'ed Alaraj
Ra'ed Alaraj

Reputation: 173

Directory.EnumerateFiles returns 0 files in UWP

In my console application I use

var allFiles = Directory.EnumerateFiles(directoryPath, "*.*", SearchOption.AllDirectories).ToList();

to return the path of each file in a folder (and in all sub-folders).

However in UWP, using the same thing returns 0

    FolderPicker folderPicker = new FolderPicker();
    folderPicker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
    folderPicker.FileTypeFilter.Add("*");
    StorageFolder pickedFolder = await folderPicker.PickSingleFolderAsync();
    var allFiles = Directory.EnumerateFiles(pickedFolder.Path, "*.*", SearchOption.AllDirectories).ToList();

I've made a method that uses the GetFilesAsync() and GetFolderAsync() functions but it is no where near as quick as Directory.EnumerateFiles()

 private async Task GetFilesInFolders(ObservableCollection<string> list, StorageFolder parent)
    {
        foreach (var file in await parent.GetFilesAsync())
        {
            list.Add(file.Path);
        }
        foreach (var folder in await parent.GetFoldersAsync())
        {
            await GetFilesInFolders(list, folder);
        }
    }

Why does Directory.EnumerateFiles() returns 0 files?

Upvotes: 1

Views: 392

Answers (1)

Amy Peng - MSFT
Amy Peng - MSFT

Reputation: 1902

Unlike the traditional desktop application, UWP runs sandboxed and have very limited access to the file system.

By default the UWP can only access its Local Folder like the LocalFolder/InstallationFolder... or the files and folders in the user's Downloads folder that your app created, if apps need to access others fils, we may need to use capabilities or file picker. For more information, please see File access permissions

Why does Directory.EnumerateFiles() returns 0 files?

UWP app has no direct access to the folder by using the pickedFolder.Path if the pickedFolder is not in the app's local folder. If you pick the folder from the app's local folder, your code will work fine.

Besides, using the path in the UWP may not be a good practice, it does not work for the KnownFolders like the musiclibrary,videolibrary..as well. For more information, please refer to Rob's blog: Skip the path: stick to the StorageFile.

It is recommend to use a Folder​Picker to let the user pick the folder and add it to your app's FutureAccessList or MostRecentlyUsedList, in this way the they can be reloaded later without requiring the user to go through the picker. For more information, please check: How to track recently-used files and folders.

Upvotes: 2

Related Questions