How to Get Actual Path from Uri Xamarin Android

How to get actual path from Uri xamarin android

How to get actual path from Uri xamarin android

I note that you are using MediaStore.Images.Media.ExternalContentUri property, what you want is getting the real path of Gallery Image?

If you want implement this feature, you could read my answer : Get Path of Gallery Image ?

private string GetRealPathFromURI(Android.Net.Uri uri)
{
string doc_id = "";
using (var c1 = 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 = ContentResolver.Query(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;
}

Update :

Here is a solution :

private string GetActualPathFromFile(Android.Net.Uri uri)
{
bool isKitKat = Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat;

if (isKitKat && DocumentsContract.IsDocumentUri(this, uri))
{
// ExternalStorageProvider
if (isExternalStorageDocument(uri))
{
string docId = DocumentsContract.GetDocumentId(uri);

char[] chars = { ':' };
string[] split = docId.Split(chars);
string type = split[0];

if ("primary".Equals(type, StringComparison.OrdinalIgnoreCase))
{
return Android.OS.Environment.ExternalStorageDirectory + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri))
{
string id = DocumentsContract.GetDocumentId(uri);

Android.Net.Uri contentUri = ContentUris.WithAppendedId(
Android.Net.Uri.Parse("content://downloads/public_downloads"), long.Parse(id));

//System.Diagnostics.Debug.WriteLine(contentUri.ToString());

return getDataColumn(this, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri))
{
String docId = DocumentsContract.GetDocumentId(uri);

char[] chars = { ':' };
String[] split = docId.Split(chars);

String type = split[0];

Android.Net.Uri contentUri = null;
if ("image".Equals(type))
{
contentUri = MediaStore.Images.Media.ExternalContentUri;
}
else if ("video".Equals(type))
{
contentUri = MediaStore.Video.Media.ExternalContentUri;
}
else if ("audio".Equals(type))
{
contentUri = MediaStore.Audio.Media.ExternalContentUri;
}

String selection = "_id=?";
String[] selectionArgs = new String[]
{
split[1]
};

return getDataColumn(this, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
{

// Return the remote address
if (isGooglePhotosUri(uri))
return uri.LastPathSegment;

return getDataColumn(this, uri, null, null);
}
// File
else if ("file".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
{
return uri.Path;
}

return null;
}

public static String getDataColumn(Context context, Android.Net.Uri uri, String selection, String[] selectionArgs)
{
ICursor cursor = null;
String column = "_data";
String[] projection =
{
column
};

try
{
cursor = context.ContentResolver.Query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.MoveToFirst())
{
int index = cursor.GetColumnIndexOrThrow(column);
return cursor.GetString(index);
}
}
finally
{
if (cursor != null)
cursor.Close();
}
return null;
}

//Whether the Uri authority is ExternalStorageProvider.
public static bool isExternalStorageDocument(Android.Net.Uri uri)
{
return "com.android.externalstorage.documents".Equals(uri.Authority);
}

//Whether the Uri authority is DownloadsProvider.
public static bool isDownloadsDocument(Android.Net.Uri uri)
{
return "com.android.providers.downloads.documents".Equals(uri.Authority);
}

//Whether the Uri authority is MediaProvider.
public static bool isMediaDocument(Android.Net.Uri uri)
{
return "com.android.providers.media.documents".Equals(uri.Authority);
}

//Whether the Uri authority is Google Photos.
public static bool isGooglePhotosUri(Android.Net.Uri uri)
{
return "com.google.android.apps.photos.content".Equals(uri.Authority);
}

Get the actual path in OnActivityResult :

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == 0)
{
var uri = data.Data;
string path = GetActualPathFromFile(uri);
System.Diagnostics.Debug.WriteLine("Image path == " + path);

}
}

How do I find the file path to my selected image using C# in Xamarin.Android?

The following worked for me:

private void AddImage_Click(object sender, EventArgs args)
{
Intent intent = new Intent();
intent.SetType("image/*");
intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(intent, "Select Picture"), 1);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if ((requestCode == 1) && (resultCode == Result.Ok) && (data != null)
{
Android.Net.Uri uri = data.Data;
string path = GetPathToImage(uri);
Blob.UploadFileInBlob(path);
}
}
private string GetPathToImage(Android.Net.Uri uri)
{
ICursor cursor = ContentResolver.Query(uri, null, null, null, null);
cursor.MoveToFirst();
string document_id = cursor.GetString(0);
if (document_id.Contains(":"))
document_id = document_id.Split(':')[1];
cursor.Close();

cursor = ContentResolver.Query(
MediaStore.Images.Media.ExternalContentUri,
null, MediaStore.Images.Media.InterfaceConsts.Id + " = ? ", new string[] { document_id }, null);
cursor.MoveToFirst();
string path = cursor.GetString(cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Data));
cursor.Close();

return path;
}
public class Blob
{
public static async void UploadFileInBlob(string path)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("[string here]");
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("[Your container here]");
await container.CreateIfNotExistsAsync();
CloudBlockBlob blockBlob = container.GetBlockBlobReference("[Your Blob reference here]");
await blockBlob.UploadFromFileAsync(path);
}
}

Note: Be sure to grant READ_EXTERNAL_STORAGE under Required permissions in the Android Manifest through the project properties. Also, enable the Storage permission on your device for the app. Remember to add the file extension (e.g. jpg) to path or whatever variable you are using.

How to get the Full file path from URI

Use:

String path = yourAndroidURI.uri.getPath() // "/mnt/sdcard/FileName.mp3"
File file = new File(new URI(path));

or

String path = yourAndroidURI.uri.toString() // "file:///mnt/sdcard/FileName.mp3"
File file = new File(new URI(path));


Related Topics



Leave a reply



Submit