[英]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.