Android File Path (Xamarin)

2019-04-13 20:34发布

I'm currently trying to select a file with an Intent. My Problem is, that the path returned is not in the right format.

My Intent:

private void selectAudioFile(object sender, EventArgs eventArgs)
{
    Intent = new Intent();
    Intent.SetType("audio/*");
    Intent.SetAction(Intent.ActionGetContent);
    StartActivityForResult(Intent.CreateChooser(Intent, "Select Audio File"), PickAudioId);
}

And the rusult method:

protected override void OnActivityResult (int requestCode, Result resultCode, Intent data) {
    base.OnActivityResult (requestCode, resultCode, data);
    if ((resultCode == Result.Ok) && (requestCode == PickAudioId) && (data != null)) {
        Android.Net.Uri uri = data.Data;
        if (!File.Exists(uri)) {
            // error
        }
    }
}

The Problem:

I need to handle the received path with the File class. The path looks like /document/audio:1234. If I check the path with File.Exists(uri) it sais that the file does not exist.

How can i get the path to this file in a format i can handle with File like /storage/emulated/0/Music/foo.mp3 or something like that ?

Thanks for help

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-13 21:00

The uri you get in return may look like a path but it's not, it's more like a shortcut to a database record.

To retrieve a real path is quite a mouthful, you've got to use a ContentResolver, here's how to retrieve it (based on that sample from Xamarin) :

    protected override void OnActivityResult (int requestCode, Result resultCode, Intent data) {
        base.OnActivityResult (requestCode, resultCode, data);
        if ((resultCode == Result.Ok) && (requestCode == PickAudioId) && (data != null)) {

            string path = GetPathToImage(data.Data);

            if (!File.Exists (path)) {
                Log.Debug ("","error");
            } else {
                Log.Debug ("","ok");
            }
        }
    }

    private string GetPathToImage(Android.Net.Uri uri)
    {
        string path = null;
        // The projection contains the columns we want to return in our query.
        string[] projection = new[] { Android.Provider.MediaStore.Audio.Media.InterfaceConsts.Data };
        using (ICursor cursor = ManagedQuery(uri, projection, null, null, null))
        {
            if (cursor != null)
            {
                int columnIndex = cursor.GetColumnIndexOrThrow(Android.Provider.MediaStore.Audio.Media.InterfaceConsts.Data);
                cursor.MoveToFirst();
                path = cursor.GetString(columnIndex);
            }
        }
        return path;
    }

you can also add other Android.Provider.MediaStore.Audio.Media.InterfaceConsts.XXX values to get more info about the file

++

查看更多
登录 后发表回答