簡體   English   中英

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://learn.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.";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM