3

I have and Xamarin Android application that needs the users to get a file from the internal storage and then read the file.

The file picker I'm using returns the file as an Android.Net.Uri object. Here's how the object is coming:

enter image description here

Then to read the file I'm using System.IO.File.ReadAllBytes(filename). The problem is that this method cannot find the file with this path.

I tried Path.GetFullPath(uri.Path) but it returns the same value I'm passing in.

How can I get the absolute path of the file for such Uri object?

Also, the file could be in any folder, not only in the Download folder as in the example.

rbasniak
  • 4,484
  • 11
  • 51
  • 100

1 Answers1

1

I had the same issue and finally found a good solution approach here:

Xamarin Choose Image From Gallery Path is Null

Only tricky part for me was: a) find the ContentResolver, as I am not in an Activity, but in a fragment:

this.View.Context.ContentResolver

b) find ManagedQuery Object, which is also a property of the Activity

this.Activity.ManagedQuery

c) provide correct selection, as I had an image it was from the MediaStore:

string selection = Android.Provider.MediaStore.Images.Media.InterfaceConsts.Id + " =? ";

I hope this still helps you, although it was 2 months ago.

private string GetPathToImage(Android.Net.Uri uri) {
    string doc_id = "";
    using (var c1 = this.View.Context.ContentResolver.Query(uri, null, null, null, null)) {
        c1.MoveToFirst();
        String document_id = c1.GetString(0);
        doc_id = document_id.Substring(document_id.LastIndexOf(":") + 1);
    }

    string path = null;

    // The projection contains the columns we want to return in our query.
    string selection = Android.Provider.MediaStore.Images.Media.InterfaceConsts.Id + " =? ";
    using (var cursor = this.Activity.ManagedQuery(Android.Provider.MediaStore.Images.Media.ExternalContentUri, null, selection, new string[] { doc_id }, null)) {
        if (cursor == null) return path;
        var columnIndex = cursor.GetColumnIndexOrThrow(Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data);
        cursor.MoveToFirst();
        path = cursor.GetString(columnIndex);
    }
    return path;
}
Community
  • 1
  • 1
Lepidopteron
  • 6,056
  • 5
  • 41
  • 53
  • It says the `ManagedQuery` line is deprecated, do you perhaps have the new way to query? – Pierre Jun 13 '17 at 05:26
  • 1
    https://stackoverflow.com/questions/12714701/deprecated-managedquery-issue Have a look here, I think this.Activity.ContentResolver.Query should be the proper replacement - https://stackoverflow.com/a/26120999/464016 – Lepidopteron Jun 13 '17 at 06:51