Search code examples
c#saveuwpaccess-denieddocumentsdirectory

UWP save file in Documents and Pictures Library


I'm trying to make a UWP app which can export a file saved in his own storage into the document library.

In Package.appxmanifest I've inserted the following lines:

<uap:Capability Name="picturesLibrary" />
<uap:Capability Name="documentsLibrary" />

The code to get the path is this:

StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.DocumentsLibrary);            
string path = storageFolder.Path + "\\" + fileName; 

The code to save the file is this:

FileStream writer = new FileStream(filePath, FileMode.Create);

At this point, the program launches this exception:

Access to the path 'C:\Users\luca9\AppData\Roaming\Microsoft\Windows\Libraries\Documents.library-ms' is denied.

On my 950XL, the exception is similar:

Access to the path 'C:\Data\Users\DefApps\APPDATA\ROAMING\MICROSOFT\WINDOWS\Libraries\Documents.library-ms' is denied.

I've tryied both on Documents and Pictures libraries, but I get the same exception.

How can I solve it?

Thank you in advance,

Luca


Solution

  • Don't get FileStream with path - the app doesn't have privileges. As you already have StorageFolder, use it to create a StorageFile and then get stream from it with one of its methods, for example:

    var file = await storageFolder.CreateFileAsync("fileName");
    using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
    {
        // do what you want
    }