简体   繁体   English

Xamarin.Forms - 使用默认应用打开文件

[英]Xamarin.Forms - Open file with default app

I need to open a file from storage.我需要从存储中打开一个文件。 I used Launcher.OpenAsync() , but it always tries to open the file in PDF reader.我使用Launcher.OpenAsync() ,但它总是尝试在 PDF 阅读器中打开文件。 Is there any other way to open a file with default app on Android?有没有其他方法可以在 Android 上使用默认应用程序打开文件?

This is the code I have already tried.这是我已经尝试过的代码。

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

 Launcher.OpenAsync
                (new OpenFileRequest()
                {
                    File = new ReadOnlyFile(path)
                }
            );
//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]; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM