Problem accessing mp3 files in WinRT app.
‘System.UnauthorizedAccessException’ occurs when app tries to open a mp3 file by name in the same folder as a file returned by FileOpenPicker. Put another way, the user picks an info file in Documents with the same name as a mp3 file. App opens the info file just fine but cannot open the mp3 file.
For example: I have a pair of files (file1.info) and (file1.mp3). A filepicker allows selecting a (*.info) file.
The user selects (file1.info). The app then opens both (file1.info) and (file1.mp3). Both files reside in a DocumentsLibrary folder, but are NOT in the MusicLibrary. The problem is when I try to open (file1.mp3) I get the ‘UnauthorizedAccessException’.
To prepro the issue:
Files:
Copy an mp3 file to Documents.
Create a text file with the same base name as the mp3 file and change its extension to .info.
In Package.appxmanifest > Declarations add a ‘File Type Associations’ declaration. Check ‘Open is safe’. Add
supported file types ‘.mp3’ and ‘.info’. Leave ‘Content type’ empty.
Code:
Dim file as StorageFile
Dim fileopenpicker As FileOpenPicker
Dim infofile As StorageFile
Dim mp3file As StorageFile
Dim filename As String
fileopenpicker = New FileOpenPicker()
fileopenpicker.FileTypeFilter.Add(".info")
fileopenpicker.FileTypeFilter.Add(".mp3")
fileopenpicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary
file = Await fileopenpicker.PickSingleFileAsync()
If file.Path.EndsWith(".info") Then
infofile = file
filename = file.Path.Substring(0, file.Path.Length - 4) & "mp3"
' This command fails with 'System.UnauthorizedAccessException'
mp3file = Await StorageFile.GetFileFromPathAsync(filename)
Else 'file is an mp3 file
mp3file = file
filename = file.Path.Substring(0, file.Path.Length - 3) & "info"
' This command succeeds!
infofile = Await StorageFile.GetFileFromPathAsync(filename)
End If
So it appears that there is some specific problem with opening an mp3 file when the file is not actually chosen by the fileopenpicker.
I checked this issue with an app that has the capability Documents Library and the filetypes .mp3 and .info declared. I figured out that it seems to be a very strange bug. If you pass the path to the documents library folder using an uppercase drive letter after having opened a FileOpenPicker you get an UnauthorizedAccessException. Using the path with a lowercase drive letter works. Strangely you can use an uppercase drive letter before having opened a FileOpenPicker.
So the workaround is to lowercase the path.
Here’s the code I used (C#):