visual-studio - 如何在 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";
推荐阅读
- android - 我的网站是(http)形式,但它在(android studio)中询问(https)不起作用
- nix - Nix 如何将单个 NPM 包安装为独立软件?
- ngx-bootstrap - 如何修复 ngx-bootstrap “无法解决”错误
- mongoose - 猫鼬关闭自动创建集合(表)
- entity-framework - EntityFramework,使用复合键创建实体的问题
- sql - PL/pgSQL:为什么我收到“设置返回函数”消息错误?
- keycloak - 获取令牌时忽略领域策略
- kotlin - 如何将 String 转换为 Int,以便用作 RoomDatabase 的 uid
- node.js - 如何正则表达式将带有“++++”、“+++”作为组分隔符的文本输入文件转换为 CSV 或 JSON
- git - 如果文件大小超过给定大小,则禁止 GitHub 推送