Why StorageFile.GetFilesAsync() crash in dll?

0

I have made a dll of UWP and using the StorageFile.GetFilesAsync() in it.

Here is the code:

Task.Factory.StartNew(async () =>
{
    StorageFolder SFolder = KnownFolders.RemovableDevices;
    try
    {
        IReadOnlyList<StorageFile> SFile = await SFolder.GetFilesAsync();
    }
    catch (Exception ex)
    {
        throw ex;
    }
}); 

After I ran the program, it crashed with the exception:

{System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

It seems I have no permission to access the file. However, I checked the UWP program which referenced the dll, the UWP program has already declared the Capabilities of Removable Storage yet.

enter image description here

What's wrong with it? Would you please tell me how to solve this? Thank you.

uwp
asked on Stack Overflow Nov 11, 2018 by 102425074 • edited Nov 12, 2018 by Martin Zikmund

1 Answer

1

As the documentation states, there are two prerequisites for using the KnownFolders.RemovableDevices folder:

To access the removable devices folder, you must:

  • In the app manifest, specify the Removable Storage capability.
  • In the app manifest, register at least one File Type Association declaration. This declaration explicitly indicates the file types (extensions) that your app wants to access on the removable devices. The app can only enumerate, create, or change files that have the file types declared in the app manifest. For more info, see Handle file activation.

According to your question, you have handled the first prerequisite, but you also need to satisfy the second - which is specifying the file types your app works with. This can be done in the Package.appxmanifest Declarations tab. There you select File Type Associations in the drop down and fill out the required fields.

The reason access to removable storage is limited to only the file types you specify is an additional security measure, so that the user can rest assured that the app does not do anything harmful. If you need full access to a file system location, you will need to use the built-in FolderPicker or use the broadFilesystemAccess capability (which is however a restricted capability and it is verified during Microsoft Store certification, whether the app has actually a good reason to declare it).

answered on Stack Overflow Nov 12, 2018 by Martin Zikmund

User contributions licensed under CC BY-SA 3.0