UWP StorageFile.OpenAsync Access Denied Issue

0

I'm running into an issue where I can read from a file in the app install directory but can't write to it.

In the below code, I open a file for reading, do stuff, dispose of my stream pointers, then try to open the file for writing.

//Open file for reading
var SocStorageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///LastSoc.txt"));
var SocInputStream = await SocStorageFile.OpenReadAsync();
var SocClassicStream = SocInputStream.AsStreamForRead();
var SocStream = new StreamReader(SocClassicStream);

<do stuff with file read>
.....

SocInputStream.Dispose();
SocClassicStream.Dispose();
SocStream.Dispose();

//Open record file for writing
var RandomAccessStream = await 
SocStorageFile.OpenAsync(FileAccessMode.ReadWrite);

When I try the last line to enable write access, I get:

System.UnauthorizedAccessException: 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'

Worried that my Dispose() methods didn't completely clean it up, I tried commenting out all my read accesses. Same error. (Yeah I know, i should use 'using' but I don't think that's the problem here)

I'm not sure why I can't obtain write access. Advice appreciated thanks!

c#
uwp
asked on Stack Overflow Sep 21, 2018 by Stephen Lam

1 Answer

1

From the path specified in your code, it looks like you are attempting to write to a file that is part of your app's package. This file exists in the installation folder of your app which you only have read only access to.

Simply put, you can read application files in the installation directory but you can't write to files in that directory. This is also true for creating new files in the app installation directory.

Have a look at this doc from Microsoft explaining file access in UWP: https://docs.microsoft.com/en-us/windows/uwp/files/file-access-permissions

From the doc linked above, the important part is:

The app's install directory is a read-only location. You can't gain access to the install directory through the file picker.

Now, if you are planning on updating this file's content, you should move it to the Application Data folder ( ApplicationData.Current.LocalFolder ). UWP apps are allowed to read and write (and create new files) in that directory.

answered on Stack Overflow Sep 21, 2018 by MrCSharp

User contributions licensed under CC BY-SA 3.0