How do I get the bytes array when I have a uri object in Xamarin.Android?

Viewed 520

I want to register a custom file association and process the file. To process the file I need the bytes array behind the file.

I successfully registered myself for a custom .xmoo extension via:

[IntentFilter(new[] { Intent.ActionView }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = "application/*", DataPathPattern = "*.xmoo")]  
public class SplashActivity : AppCompatActivity
{
    public override void OnCreate(Bundle savedInstanceState, PersistableBundle persistentState)
    {
        base.OnCreate(savedInstanceState, persistentState);
        Android.Net.Uri fileUri = Intent.Data;

Now, I'm however at a loss of how I get the bytes array from the Uri. What's the canonical way to read the bytes?

1 Answers

If I am not wrong converting it to a memory stream and then to byte array might do the trick:

Something like this:

public byte[] UriToByteArrayConverter(Android.Net.Uri uri)
{
  Stream stream = ContentResolver.OpenInputStream(uri);   
  byte[] byteArray;

  using (var memoryStream = new MemoryStream())
  {
     stream.CopyTo(memoryStream);
     byteArray = memoryStream.ToArray();
  }
    return byteArray;
}

In case it does not work kindly revert.

Related