Xamarin.Forms - Open file with default app

和自甴很熟 提交于 2021-01-29 17:48:41

问题


I need to open a file from storage. I used Launcher.OpenAsync(), but it always tries to open the file in PDF reader. Is there any other way to open a file with default app on Android?

This is the code I have already tried.

private void OpenDocument(string filePath)
{
    var localFile = "file://" + filePath;
    Launcher.OpenAsync(localFile);
}

回答1:


string path = "yuor uri bla-bla-bla";

await Launcher.OpenAsync(new OpenFileRequest

{

File = new ReadOnlyFile(path)

});




回答2:


        //Dictionary with extensions
        static private Dictionary<string, string> filesType = new Dictionary<string, string>
        {
            { ".doc", "application/msword" },
            { ".jpg", "image/jpeg" },
            { ".jpeg", "image/jpeg" },
            { ".log", "text/plain" },
            { ".mp3", "audio/mp3" },
            { ".mp4", "video/mp4" },
            { ".pdf", "application/pdf" },
            { ".png", "image/png" },
            { ".rar", "application/x-rar-compressed" },
            { ".rtf", "application/rtf" },
            { ".txt", "text/plain" },
            { ".zip", "application/zip" },
        };

        //Open document
        static public void OpenDocument(string filePath)
        {
            var localFile = "file://" + filePath;

            Intent intent = new Intent();
            intent.AddFlags(ActivityFlags.NewTask);
            intent.SetAction(Intent.ActionView);
            string type = GetType(filePath);
            intent.SetDataAndType(Android.Net.Uri.Parse(localFile), type);
            Android.App.Application.Context.StartActivity(intent);
        }

        //Get file extesion
        static private string GetType(string filePath)
        {
            string extinsion = "";
            for (int i = filePath.Length - 1; i >= 0; i--)
            {
                if (filePath[i] != '.')
                    extinsion += filePath[i];
                else
                    break;
            }

            string reversedExtinson = ".";
            for (int i = extinsion.Length - 1; i >= 0; i--)
                reversedExtinson += extinsion[i];

            return filesType[reversedExtinson];
        } 


来源:https://stackoverflow.com/questions/57987659/xamarin-forms-open-file-with-default-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!