Search code examples
c#uwpmicrosoft-graph-apionedrivemicrosoft-graph-files

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


I'm working on this exercise from Microsoft Graph team: Access and download files from OneDrive. And I'm getting the following Access denied error on the following code at the end under the section: 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.

Remarks with Question: Error occurs at line var driveItemFile = System.IO.File.Create(driveItemPath); of the code below. I know that UWP apps can access certain file system locations by default. Apps can also access additional locations through the file picker, or by declaring capabilities as explained here. According to this official link, one of those default locations is Application install directory which during debug mode is supposed to be ...\bin\debug folder. And the above linked tutorial from MS Graph team does not mention declaring a capability in the app's Package.appxmanifest file. So, why the error and how can we resolve it without declaring broadFileSystemAccess capability - as you don't want go free for all scenario?

Code:

// 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);

Solution

  • Use ApplicationData.Current.LocalFolder.Path instead of System.IO.Directory.GetCurrentDirectory(). The default location is C:\Users\username\AppData\Local\Packages\your package name\LocalState