如何解决如何访问Xamarin Forms中共享项目中存储的文件?
我在共享项目中有一个名为Documentation的文件夹,在本例中为App2。如何访问文档文件夹中存储的文件?下图为项目结构。
我已经尝试了以下命令,但是它们不起作用:
System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
AppDomain.CurrentDomain.BaseDirectory
System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
如果访问该文件夹中的文件很麻烦,我很乐意听到其他选择。
解决方法
这是我对共享项目中的JSON文件(使用PCL)进行的操作。正如Jason在评论中指出的那样,如果您使用的是.NET Standard,则只需在共享项目中定义GetSharedFile
方法,而不用创建平台特定的引用。
-
将文件添加到共享项目并将其设置为
Embedded Resource
-
在共享项目中创建一个
IFileHelper
界面
public interface IFileHelper {
Stream GetSharedFile(string fileResourceName);
}
- 使用以下内容在每个项目(Android和iOS)中创建一个新的
FileHelper
类
public class FileHelper : IFileHelper {
public Stream GetSharedFile(string fileResourceName) {
Type type = typeof(IFileHelper); // We could use any type here,just needs to be something in your shared project so we get the correct Assembly below
return type.Assembly.GetManifestResourceStream(fileResourceName);
}
}
- 在共享项目中添加文档处理程序类。如下所示(请确保更改
App
命名空间以匹配您的命名空间):
public class Documentation {
private const string ResourcePath = "App.Documentation.index.html"; // App would be your application's namespace,you may need to play with the Documentation path part to get it working
public string GetDocs() {
IFileHelper helper = DependencyService.Get<IFileHelper>(); // Your platform specific helper will be filled in here
Stream stream = helper.GetSharedFile(ResourcePath);
using (stream)
using (StreamReader reader = new StreamReader(stream)) {
return reader.ReadToEnd(); // This should be the file contents,you could serialize/process it further
}
}
}
我主要是手工编写的,因此请让我知道是否有任何问题。如果您无法加载文件,建议尝试将其放入共享项目的根目录中,然后将上面代码中的ResourcePath
更改为以下内容(再次使用应用程序的名称空间而不是App
):
private const string ResourcePath = "App.index.html";
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。