Search code examples
c#uwpfile-permissions

UWP: Write file in a generic location using StorageApplicationPermissions.FutureAccessList


I have the following scenario in my UWP App:

  1. The user imports a file (e.g. using a FilePicker, or by dragging a file onto the app, etc.) into my application.

  2. We save some metadata of this file inside our internal database, and we also save a token retrieved using the following code:

    string token = StorageApplicationPermissions.FutureAccessList.Add(file);
    
  3. The user closes the app.

  4. The user re-opens the app.

  5. Now we want to overwrite the initial file. To do this, we retrieve the StorageFile using this code:

    StorageFile exportTarget = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(token);
    

but when I try to write into the file, e.g. using

using (IRandomAccessStream fs = await exportTarget.OpenAsync(FileAccessMode.ReadWrite))

I get an exception complaining that exportTarget is ReadOnly.

How can I have access to such file in Write mode?


Solution

  • It turned out it was not a strict problem of the StorageApplicationPermissions.FutureAccessList.

    The problem happens in fact only if the user imports a file by dragging-and-dropping the file into the app: in this case, the DataPackageView.GetStorageItemsAsync() method returns a list of StorageFile that are ReadOnly.

    So, the only way to overwrite those files is by using PathIO methods, as described in this post: https://github.com/microsoft/microsoft-ui-xaml/issues/2421