UWP 将文件保存在文档和图片库中

UWP save file in Documents and Pictures Library

我正在尝试制作一个 UWP 应用程序,它可以将保存在自己存储中的文件导出到文档库中。

在 Package.appxmanifest 中,我插入了以下几行:

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

获取路径的代码是这样的:

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

保存文件的代码是这样的:

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

此时,程序启动异常:

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

在我的 950XL 上,异常情况类似:

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

我已经尝试过文档库和图片库,但我遇到了同样的异常。

我该如何解决?

提前谢谢你,

卢卡

不要获取带有路径的 FileStream - 该应用程序没有权限。由于您已经拥有 StorageFolder,请使用它来创建 StorageFile,然后使用其中一种方法从中获取流,例如:

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

Microsoft 的这个示例使用 uwp。

https://docs.microsoft.com/en-us/windows/uwp/files/quickstart-save-a-file-with-a-picker

1.创建和自定义 FileSavePicker

var savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.SuggestedStartLocation =
Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "New Document";

2。显示 FileSavePicker 并保存到选取的文件

Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
    // Prevent updates to the remote version of the file until
    // we finish making changes and call CompleteUpdatesAsync.
    Windows.Storage.CachedFileManager.DeferUpdates(file);
    // write to file
    await Windows.Storage.FileIO.WriteTextAsync(file, file.Name);
    // Let Windows know that we're finished changing the file so
    // the other app can update the remote version of the file.
    // Completing updates may require Windows to ask for user input.
    Windows.Storage.Provider.FileUpdateStatus status =
        await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);
    if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
    {
        this.textBlock.Text = "File " + file.Name + " was saved.";
    }
    else
    {
        this.textBlock.Text = "File " + file.Name + " couldn't be saved.";
    }
}
else
{
    this.textBlock.Text = "Operation cancelled.";
}