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.

2
  • Can you provide the file picker code of your project? Commented Feb 20, 2017 at 2:49
  • I think the way to go is: 1. File f = new File(Uri); var absp = f.AbsolutePath; Commented Jun 13, 2017 at 4:49

1 Answer 1

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; } 
Sign up to request clarification or add additional context in comments.

2 Comments

It says the ManagedQuery line is deprecated, do you perhaps have the new way to query?
stackoverflow.com/questions/12714701/… Have a look here, I think this.Activity.ContentResolver.Query should be the proper replacement - stackoverflow.com/a/26120999/464016

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.