0
using Xamarin.Essentials;

namespace myNamespace
{
    class myClass
    {
        public async void OpenFile(string path)
        {
            await Launcher.OpenAsync(new OpenFileRequest("File", new ReadOnlyFile(path)));
        }
    }
}

It works well if path is a real file system path, and doesn't work if it is a URI, giving an error like:

System.IO.DirectoryNotFoundException: 'Could not find a part of the path "content://com.android.providers.downloads.documents/something".'

(I'm getting path using Xamarin.Plugin.FilePicker, so it should be a real file, but sometimes the FilePicker returns URI instead of a path. For example, if I pick an image from camera it returns a path, and if I pick a file from Downloads, it returns a URI).

mrbus2007
  • 197
  • 7

1 Answers1

0

I found the solution myself. File can be launched using ActionView intent if the 'path ' is a content URI.

namespace myNamespace
{
    class myClass
    {
        public void OpenFile(string path)
        {
            var uri = Android.Net.Uri.Parse(path);
            var intent = new Intent(Intent.ActionView, uri);
            intent.AddFlags(ActivityFlags.GrantReadUriPermission);
            if (intent.ResolveActivity(Activity.PackageManager) != null)
                StartActivity(intent);
        }
    }
}

If it is a path, your app must be a FileProvider to use this method, as stated here: android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

In this case, use Xamarin.Essentials.Launcher because it adds FileProvider functionality to your app.

mrbus2007
  • 197
  • 7