Search code examples
c#uwpwindows-10-mobile

Access to file denied on app's second run


I'm facing a weird issue, when trying to access file on SD card with code:

var path = @"D:\Test\test.txt";
try
{
    StorageFile file = await StorageFile.GetFileFromPathAsync(path);
}
catch (Exception ex) { Debug.WriteLine($"File access failed due to {ex.Message}"); }

path = @"Test\test.txt";
StorageFile file2 = await (await KnownFolders.RemovableDevices.GetFoldersAsync()).FirstOrDefault().GetFileAsync(path);

The file is on SD card, I've declared RemovableStorage capability, and added FileTypeAssociation. I can get the file when I first debug the app, but on the second run I get UnauthorizedException with the first StorageFile. Amazingly the second try to get the file via RemovableStorage works every time. If I only restart the phone and debug app once again - it will again work, but still only for the first time.

Is accessing files by StorageFile.GetFileFromPathAsync() somehow limited? Am I missing something?


UPDATE:

Seems like on newest version of emulator 10856 I get an exception on every run, what may mean that there will be no way to access file via full path.


Solution

  • The picker allows access because the user provided the file to you, not the path. A winstore app should not be dependent upon a users drive / folder layout, that is why you don't have authority to access files by absolute path. In this case, we should firstly allow access to removable devices in manifest file, then we should use system's RemovebleDevices folder to access files of allowable types.

    Also it is strange you can work with the absolute path the first time. In my test device, I always get the UnauthorizedAccessException and "Access is denied" error if using absolute path. My device is of build 10586.11.