UWP - OneDrive file download error: “Access to the path '…' is denied” when using sample code from MS Graph team

UWP - OneDrive file download error: “Access to the path '…' is denied” when using sample code from MS Graph team

我正在做 Microsoft Graph 团队的这个练习:Access and download files from OneDrive。我在本节末尾的以下代码中收到以下访问被拒绝错误:Download a file from the user's OneDrive:

Access to the path 'C:\DotNETCore2019\UWP\AccessFilesTrainingCourse\bin\x86\Debug\AppX\driveItem_17B6A4972C38846A!2923.file' is denied.

有问题的备注:错误发生在下面代码的第var driveItemFile = System.IO.File.Create(driveItemPath);行。我知道 UWP 应用默认可以访问某些文件系统位置。应用程序还可以通过文件选择器或通过声明功能来访问其他位置,如 here 所述。根据官方 link,这些默认位置之一是 Application install directory,在调试模式下应该是 ...\bin\debug 文件夹。上面来自 MS Graph 团队的 linked 教程没有提到在应用程序的 Package.appxmanifest 文件中声明功能。那么,错误的原因以及我们如何解决它 without 声明 broadFileSystemAccess 功能 - 因为您不想在所有情况下都免费?

代码:

// request 3 - download specific file
var fileId = "REPLACE_THIS"; //I have correctly placed corresponding fileid here
var request = client.Me.Drive.Items[fileId].Content.Request();

var stream = request.GetAsync().Result;
var driveItemPath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "driveItem_" + fileId + ".file");
var driveItemFile = System.IO.File.Create(driveItemPath);
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(driveItemFile);
Console.WriteLine("Saved file to: " + driveItemPath);

使用 ApplicationData.Current.LocalFolder.Path 而不是 System.IO.Directory.GetCurrentDirectory()。默认位置是 C:\Users\username\AppData\Local\Packages\your package name\LocalState