Stefan Meyer Stefan Meyer - 7 months ago 41
Vb.net Question

Windows Universal App: Opening a file on USB Drive

I want to select a XML-File on a USB-Drive and then open and read it. I think I have a misunderstanding of the concept in Universap Apps.

When I use this code, I get the error "Access to the path 'E:\folder\file.xml' is denied." when trying to load it.

Dim picker As Windows.Storage.Pickers.FileOpenPicker = New Windows.Storage.Pickers.FileOpenPicker
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail
picker.FileTypeFilter.Add(".xml")
Dim File As Windows.Storage.StorageFile = Await picker.PickSingleFileAsync
Await Task.Run(Function()
If Not (File Is Nothing) Then
Task.Yield()
Dim loadedData As XDocument = XDocument.Load(File.Path)
End If
End Function)


I my understanding, file access is granted, when a file is selected using the picker. So perhaps it is, because I access it in Task.Run?

When I put the picker.PickSingleFileAsync into the function it does not work, because I can not call it using await. After removing the await I get a cast error "Unable to cast object of type 'System.__ComObject' to type 'Windows.Storage.StorageFile'."

What is my conceptional error and how can I select a file using the picker (or do I have to use something else than the picker?) and open and read it (xml)? If it is important: the code should be placed in the click event of a button.

Answer

You have only access to File object.
You can access file by it's path.

This way should work:

    Dim picker As Windows.Storage.Pickers.FileOpenPicker = New Windows.Storage.Pickers.FileOpenPicker
    picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail
    picker.FileTypeFilter.Add(".xml")
    Dim File As Windows.Storage.StorageFile = Await picker.PickSingleFileAsync

    Dim Fl = Await File.OpenAsync(Windows.Storage.FileAccessMode.Read)
    Dim inStream As Stream = Fl.AsStreamForRead()

    Dim loadedData As XDocument = XDocument.Load(inStream)
Comments