【发布时间】:2021-06-15 11:57:31
【问题描述】:
我有一个从 API 下载并使用 Environment.SpecialFolder.MyDocuments 保存到内部存储的 PDF 文件。当我尝试打开文件时,标题中出现错误,Failed to find configured root that contains /data/data/com.app.myapp/files/myfile.pdf。
保存文件的代码:
var filePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), fileName);
System.IO.File.WriteAllBytes(filePath, fileBytes);
LaunchIntent(filePath);
发生错误的代码:
public static void LaunchIntent(string fileLocation)
{
// now create an activity which points to the file
var localPath = global::Android.Net.Uri.Parse(fileLocation).Path;
File javaFile = new File(localPath);
//error occurs at below code
var filePath = global::Android.Support.V4.Content.FileProvider.GetUriForFile(
CrossCurrentActivity.Current.Activity,
CrossCurrentActivity.Current.Activity.PackageName + ".fileprovider",
javaFile);
var actionView = new Intent(Intent.ActionView);
actionView.AddFlags(ActivityFlags.GrantReadUriPermission);
var extension = localPath.Substring(localPath.LastIndexOf('.') + 1);
var mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
actionView.SetDataAndType(filePath, mimeType);
CrossCurrentActivity.Current.Activity.StartActivity(actionView);
}
我的文件路径文件:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external" path="." />
<external-files-path name="external_files" path="." />
<cache-path name="cache" path="." />
<external-cache-path name="external_cache" path="."/>
</paths>
【问题讨论】:
-
为什么要以两种完全不同的方式构建文件路径?
-
我不确定你的意思,对android来说还是很新的。你能告诉我我做错了什么吗?
-
第一个sn-p和第二个snipped中构建文件路径的方式完全不同。为什么您不在两者中使用相同的方法?
-
我更新了代码,以便提供更好的画面。由于
GetUriForFile()的方法参数要求,我不会以相同的方式构建它们 -
对不起,我没有做过这样的代码,所以只能给出一般的调试建议。在第一个代码 sn-p 中,
filePath的值是多少?您是否使用文件浏览器应用程序来验证文件是否在您期望的位置?文件的实际位置是否与错误消息中的路径相同?如果没有,您是否找到了验证错误消息中的路径应该映射到物理位置的文档?您能否找到使用 GetUriForFile 的示例应用程序,下载该应用程序并验证它是否有效?那看看它用的是什么路径?
标签: xamarin xamarin.forms xamarin.android android-fileprovider